Monday, October 9, 2023

OpenCV and Image Processing - Conversion of Color Spaces (Convert BGR to HSV and vice versa)

As explained earlier, an image can be represented not only in BGR but also in HSV color spaces, OpenCV can easily convert the image between BGR and HSV. Like converting it to grayscale, the same function cv2.cvtColor() is used but the second parameter is different, cv2.COLOR_BGR2HSV in this case.

The HSV image can also be split into three channels, hue, saturation and value. Then each channel can be adjusted to achieve some different effects, later we will explain how to adjust each channel to change the image.

Below code snippets are to convert an image to HSV color space:

1 def convert_bgr2hsv(image):

2 hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

3 return hsv 

As shown in Figure below, the color image is converted to HSV color space, and then it can be further split into three channels in hue, saturation and value by using cv2.split() function.


Convert HSV to BGR

When OpenCV displays an image, the function cv2.imshow() is used and by default in BGR color space. If an image is converted to HSV and followed by some image processing operations, it can not be directly sent to cv2.imshow() for displaying, instead it must be converted back to BGR, then sent to cv2.imshow() for displaying, otherwise the image will not be displayed correctly.

In last section an image is converted to HSV, and here we will convert it back to BGR with the same function cv2.cvtColor() but different parameter cv2.COLOR_HSV2BGR.

1 def convert_hsv2bgr(image):

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

3 return bgr


Share:

0 comments:

Post a Comment