Monday, October 2, 2023

OpenCV and Image Processing - Conversion of Color Spaces

Image processing is a technique to apply some mathematical algorithms and use various functions and techniques to manipulate digital images in order to get the desired outcomes with enhanced effects, such as improving their quality or extracting useful information from them.

OpenCV provides a number of methods for image processing, we will look into some commonly and widely used methods for image processing. 

Conversion of Color Spaces

We have already seen that the color image can be represented using either BGR or HSV color spaces, and a color image can also be converted to a grayscale image.OpenCV provides many methods for the conversion of color spaces, here we introduce two of them: BGR to and from Grayscale, and BGR to and from HSV.

Convert BGR to Gray

There are two ways to obtain a grayscale image from the color one, 1) use cv2.cvtColor() function with cv2.COLOR_BGR2GRAY as its second parameter, and 2) load the image with grayscale mode by using cv2.imread() function with cv2.IMREAD_GRAYSCALE as the second parameter.

The first method loads the color image and then converts it to grayscale, then we have both the color and grayscale images available in the memory. However, if the color image is not needed, the second method loads the image in grayscale only, the color one is not available in this case and could save some memory. Below code snippets show the two methods:

1 def convert_bgr2gray(image):

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

3 return gray

4

5 def load_image_gray(file_name):

6 gray = cv2.imread(file_name, cv2.IMREAD_GRAYSCALE)

7 return gray

Line 1 to 3 is the first method, the color image in image is passed as a parameter, cv2.cvtColor() function will convert it to grayscale one.

Line 5 to 7 is the second method, it loads the image in grayscale mode directly from the file.


As shown in Figure above, the color image (left) is converted to a grayscale one (right).

As discussed earlier, in OpenCV the default color space for an image is BGR, so a color image can be split into three channels of blue, green and red, each channel is in grayscale, as shown in Figure below.


The cv2.split() function can be used to split a color image into the three channels:

1 def split_image(image):

2 ch1, ch2, ch3 = cv2.split(image)

3 return ch1, ch2, ch3

And each channel is in grayscale.

Share:

0 comments:

Post a Comment