Monday, August 7, 2023

OpenCV basics continued...

Convert Color Image to Grayscale

An alternative way to have a grayscale image is to load the original image first, then use cv2.cvtColor() function to convert it to a grayscale image, this way we will have both original and grayscale images available for further processing. This is useful because in the future when we do the image processing, we want to process the image in grayscale mode while displaying the original color image.

Now replace the code line 2 and 3 in previous post with the following:

1 img = cv2.imread("../res/flower004.jpg")

2 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

3 cv2.imshow("Image", img)

4 cv2.imshow("Image Gray", gray)

cv2.cvtColor() is an OpenCV function used to convert an image from one color space to another, here is its syntax:

Syntax - cv2.cvtColor(src, code[, dst[, dstCn]])

Parameters

src: source image to be converted.

code: color space conversion code.

dst: optional, the output image of the same size and depth as src image.

dstCn: optional, the number of channels in the destination image. If the parameter is 0 then the number of the channels is derived automatically from src image.

cv2.COLOR_BGR2HSV/COLOR_HSV2BGR: Convert between BGR color image and HSV space.

cv2.COLOR_BGR2GRAY/COLOR_GRAY2RGB: Convert between BGR color image and grayscale image

Other conversion codes are not listed here, please reference OpenCV documents.

Return Value 

The image that is converted from the source image.

Execute the codes, the color image and grayscale image are displayed side by side, as shown below.





Share:

0 comments:

Post a Comment