1

I have a grey image and I want to convert it into RGB. How will I do it in OpenCV?

image = cv2.imread("image.jpg", cv2.IMREAD_GRAYSCALE)
cv2.imshow('Grey Scale Image', image)
cv2.waitKey()


backtorgb = cv2.cvtColor(image,cv2.COLOR_GRAY2RGB)
cv2.imshow('GRAY2RGB Image', backtorgb)
cv2.waitKey()

I tried GRAY2RGB, but it doesn't change the image. Where did I go wrong?

alyssaeliyah
  • 2,214
  • 6
  • 33
  • 80

2 Answers2

10

There's a fundamental misunderstanding here. You can't remove all the colour information and then magically re-create it from nowhere.

Once you delete it, it's gone.

So what is GRAY2RGB for? It just takes the grey channel and replicates it into the R, G and B channels, so you have a 3-channel image, but all 3 are the same, hence it looks grey.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
-1

There are other ways to do it, you don't need openCV, in the end the image is a matrix an you can do it with multiplication, look at this post: How can I convert an RGB image into grayscale in Python?

EDIT: Giving the solution in case link changes.

An image can be seen as 3 matrices, one for red, one for green and one for blue, the three channel colours RGB, each one with the information for each pixel ranging between 0 and 255. To transform it to gray scale image it is necessary to sum all the colours by the representation of their luminosity, which is a coeficient already known obtained in an ecuation system:

def rgb2gray(rgb):
    r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
    gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
    return gray

In openCV I don't know if there is a function, however this should be enough.