본문 바로가기
Lecture/OpenCV Master with Python (Beginner)

OpenCV + Python Color space conversion and color detection

by codingwalks.en 2024. 10. 24.
728x90
반응형

Hello. This is codingwalks.

In this article, we will learn about color spaces, especially the widely used RGB, CMYK, HSV, YUV, and CIELab color spaces. Additionally, we will introduce a method to detect specific colors in images using the OpenCV library. We will also explain why each color space is suitable for color detection and its application fields, and cover real-world use cases. To do this, we will convert an image file to a specific color space and use the trackbar to adjust the color range in real time to detect the desired color. We will also explain an example that can be easily implemented using Python code step by step.

 

1. Color Space and Conversion

A color space is a system that mathematically expresses color and defines hue, saturation, brightness, etc. There are various color spaces, and each color space is optimized for a specific task or device. Representative examples include RGB, CMYK, HSV, YUV, and CIELab.

1.1. RGB (Red, Green, Blue)

RGB is a color space widely used in computer monitors, digital cameras, scanners, etc., and expresses various colors by synthesizing three colors: red, green, and blue. Color, saturation, and brightness are expressed in three channels, and each channel value has a range of 0 to 255.

  • Advantages: High compatibility with displays, and is basically used in most imaging devices.
  • Application areas: Mainly used in digital cameras, monitors, and web graphics.
  • Practical examples: It is often used when expressing images by specifying colors in RGB on websites or designing user interfaces.

OpenCV functions:

img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)

1.2. CMYK (Cyan, Magenta, Yellow, Black)

CMYK is a color space mainly used in printing. Unlike RGB, it expresses colors by absorbing light rather than emitting light. It creates color by mixing four inks: Cyan, Magenta, Yellow, and Black.

  • Advantages: Colors are accurately expressed in the printing process, and it is excellent for color control of printed materials.
  • Applications: Mainly used in the printing, publishing, and packaging industries.
  • Practical examples: Used for accurate color expression in magazines, books, posters, and advertisements.

OpenCV does not directly support CMYK conversion, but it can be converted through the PIL library.

from PIL import Image
img = Image.open('image.bmp')
cmyk_image = img.convert('CMYK')

1.3. HSV (Hue, Saturation, Value)

HSV is a color space expressed as Hue, Saturation, and Value. It is often used for color detection because it can separate color information and express it clearly. Hue represents color, Saturation represents color intensity, and Value represents brightness.

  • Advantages: It is advantageous for specific color detection because it can process color, saturation, and brightness separately. It is strong against lighting changes, so it can detect colors stably.
  • Applications: Object tracking, color filtering, video analysis, etc.
  • Practical examples: HSV is widely used in video monitoring systems, car lane tracking systems, and vision-based robots.

OpenCV functions:

img_hsv = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2HSV)

1.4. YUV (Luma, Chrominance)

YUV is a color space composed of brightness (Luma, Y) and chrominance (Chrominance, U and V). Since it stores brightness and color information separately, it can reduce or compress bandwidth, so it is often used in video compression.

  • Advantages: By separating brightness and color information, efficient video compression is possible, and it is effective in reducing noise in videos.
  • Applications: Video encoding, broadcasting systems, CCTV, etc.
  • Practical examples: YUV is used in image and video compression formats such as MPEG and JPEG.

OpenCV function:

img_yuv = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2YUV)

1.4. CIELab (L, a*, b*)

CIELab is a color space designed for human vision, where L represents brightness and a* and b* represent color information. CIELab is a device-independent color space that reflects the actual color differences perceived by humans well.

  • Advantage: It is advantageous for color matching work because it expresses color differences close to human vision.
  • Application: Color correction, product quality control, color matching.
  • Practical examples: CIELab is widely used in tasks that require accurate color matching, such as photo editing, clothing design, and painting.

OpenCV function:

img_lab = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2Lab)

1.5. Splitting and Merging Channels

You can separate each color channel of an image individually, or merge the separated color channels into a single image. For example, if you use an RGB image, you can analyze or manipulate the red, green, and blue components separately by splitting the channels. You can also merge the single-channel images separated into each color channel from the image back into a single image to create a new image.

In OpenCV, you can use cv2.split() and cv2.merge() to separate and merge channels. For example, you can separate each channel of a BGR image and then change only a specific channel, or you can manipulate each channel when detecting colors after converting to HSV or another color space.

import cv2
import numpy as np

image_bgr = cv2.imread('resources/lena.bmp')

# Channel splitting (BGR)
blue_channel, green_channel, red_channel = cv2.split(image_bgr)

# Set the blue channel to 0 and merge
blue_channel[:] = 0
modified_image = cv2.merge([blue_channel, green_channel, red_channel])

cv2.imshow('Modified Image', modified_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

channel splitting
blue channel to 0 (merged image)

 

3. Color Segmentation

Now we need to set the range of colors we want to detect. In this case, we want to detect orange, and we set the minimum and maximum range of that color in the HSV color space. The problem is that we don’t know the exact HSV value of orange, so we can use the Trackbar to adjust the values ​​in real time. Additionally, we can use the Trackbar to experiment with different color spaces, and optimize for the characteristics of each color space.

import cv2
import numpy as np

# Empty function to be used in the trackbar (for trackbar callbacks)
def empty(a):
    pass

image_bgr = cv2.imread('resources/fruits.bmp')

# HSV color space conversion
image_hsv = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2HSV)

# Create a trackbar window
cv2.namedWindow("Trackbars")

# Trackbar settings (Minimum and maximum values
# for Hue, Saturation, and Value, respectively)
cv2.createTrackbar("Hue Min", "Trackbars", 0, 179, empty) # Hue ranges from 0 to 179
cv2.createTrackbar("Hue Max", "Trackbars", 179, 179, empty)
cv2.createTrackbar("Sat Min", "Trackbars", 0, 255, empty) # Saturation ranges from 0 to 255
cv2.createTrackbar("Sat Max", "Trackbars", 255, 255, empty)
cv2.createTrackbar("Val Min", "Trackbars", 0, 255, empty) # Value is in the range of 0 to 255
cv2.createTrackbar("Val Max", "Trackbars", 255, 255, empty)

while True:
    # Read values from the trackbar
    h_min = cv2.getTrackbarPos("Hue Min", "Trackbars")
    h_max = cv2.getTrackbarPos("Hue Max", "Trackbars")
    s_min = cv2.getTrackbarPos("Sat Min", "Trackbars")
    s_max = cv2.getTrackbarPos("Sat Max", "Trackbars")
    v_min = cv2.getTrackbarPos("Val Min", "Trackbars")
    v_max = cv2.getTrackbarPos("Val Max", "Trackbars")
    
    # Create arrays of minimum and maximum values
    lower = np.array([h_min, s_min, v_min])
    upper = np.array([h_max, s_max, v_max])
    
    # Detect only colors within the HSV range with a mask
    mask = cv2.inRange(image_hsv, lower, upper)
    
    # Apply the mask to the original image
    result = cv2.bitwise_and(image_bgr, image_bgr, mask=mask)
    
    cv2.imshow("Original", image_bgr)
    cv2.imshow("Mask", mask)
    cv2.imshow("Result", result)
    
    if cv2.waitKey(1) & 0xFF == ord('q'):
    	break
    
cv2.destroyAllWindows()

Color detection by adjusting the trackbar

 

4. Conclusion

In this article, we learned useful methods for converting to various color spaces and separating and merging channels using OpenCV. We checked how to convert an image to HSV color space and detect a specific color. We adjusted the color range in real time using the trackbar and filtered the detected color through a mask. In order to apply it to an actual project, it is important to understand the characteristics and conversion methods of each color space well, and select a color space suitable for image processing to perform color detection.

 

If you found this post useful, please like and subscribe below. ^^

Buy me a coffee

 

[Codingwalks]에게 송금하기 - AQR

[Codingwalks]에게 송금하기 - AQR

aq.gy

★ All contents are referenced from the link below. ★

 

OpenCV: OpenCV-Python Tutorials

Core Operations In this section you will learn basic operations on image like pixel editing, geometric transformations, code optimization, some mathematical tools etc.

docs.opencv.org

728x90
반응형