Reputation: 219
I happened to encounter this API cv2.COLOR_GRAY2RGB. I found it strange because there should have no way to convert an grey scale image to RGB image. So I tried something like this: I took an image like this:
The image is shown by plt.imshow(img) (with default arguments). Then I convert it into grey scale with cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) and get this:
I know it does not appear grey-scale looking is because imshow() by default is not displaying grey-scale image (more like heat-map I think). So I used cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) and got this:
It appears grey to out eyes despite it has three channels now. So I conclude that cv2.COLOR_GRAY2RGB is a walk-around to display grey-scale image in grey-scale fashion without changing the settings for imshow().
Now my question is, when I use cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) again to convert this three-channel gray image back to one channel, the pixel value is exactly the same as the first time I converted the original image into one channel with cv2.cvtColor(img, cv2.COLOR_BGR2GRAY):
In other words, cv2.COLOR_BGR2GRAY can do a many-to-one mapping. I wonder how is that possible.
Upvotes: 1
Views: 12262
Reputation: 2741
COLOR_BGR2GRAY
color mode estimates a gray value for each pixel using a weighted sum of B
, G
, R
channels, w_R*R+w_G*G+w_B*B=Y
per pixel. So any 3 channel image becomes 1 channel.
COLOR_GRAY2BGR
color mode basically replaces all B
, G
, R
channels with the gray value Y
, so B=Y, G=Y, R=Y
. It converts a single channel image to multichannel by replicating.
More documentation about color modes are here.
Upvotes: 4