Friday, October 6, 2023

OpenCV and Image Processing - Conversion of Color Spaces (Convert Grayscale to BGR)

A grayscale image can also be converted to BGR color space, in this case the source is a grayscale image which only has one channel and does not have any color information, therefore the result BGR image looks the same as the original grayscale one. But the difference is the BGR image has three channels although looks the same as the grayscale one, while the original gray image only has one channel.

To convert a grayscale image to BGR, use cv2.cvtColor() function with cv2.COLOR_GRAY2BGR as the second parameter.

1 def convert_gray2bgr(image):

2 bgr = cv2.cvtColor(image,cv2.COLOR_GRAY2BGR)

3 return bgr

Figure below shows the idea:


The left image is the original grayscale image, which has only one channel. The right image, however, is in BGR color space although looks same as the grayscale one, it can be split into three channels. Since the right image looks same as the left one, why we should convert it? There are several reasons to do it, sometimes in the image processing, some operations need to be performed on two or more images, it’s important that all the images are in the same color space. For example, if we want to blend, or mix, two images together, but one is color image and another is grayscale, the grayscale one must be converted into BGR before blending them.

Sometimes when you want to colorize a grayscale image, it must be converted to BGR first, then paint colors on different channels, because you are not able to paint colors on a single-channel grayscale image.

Share:

0 comments:

Post a Comment