Home >Backend Development >C++ >How can we enhance red color detection in OpenCV using HSV color space?
Enhanced Red Color Detection in OpenCV using HSV Color Space
This article aims to improve the accuracy of red color detection in images using OpenCV's HSV color space.
Problem:
Detecting a red rectangle in an image using cv::inRange and HSV color space is currently yielding unsatisfactory results. The desired outcome is to isolate the red rectangle effectively.
Solution:
In HSV, red color spans a range that wraps around the value of 180. To account for this, the HSV range should include values both in [0,10] and [170, 180].
Code Update:
The following code snippet demonstrates the updated approach:
# Include OpenCV library import cv2 # Define HSV range for red color H_MIN1 = 0 H_MAX1 = 10 H_MIN2 = 170 H_MAX2 = 180 S_MIN = 70 S_MAX = 255 V_MIN = 50 V_MAX = 255 # Read the input image image = cv2.imread('image.png') # Convert to HSV color space hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # Create masks for the two ranges of red hue mask1 = cv2.inRange(hsv, (H_MIN1, S_MIN, V_MIN), (H_MAX1, S_MAX, V_MAX)) mask2 = cv2.inRange(hsv, (H_MIN2, S_MIN, V_MIN), (H_MAX2, S_MAX, V_MAX)) # Combine the masks mask = cv2.bitwise_or(mask1, mask2) # Display the resulting mask cv2.imshow('Mask', mask) cv2.waitKey(0)
Alternative Approach: Cyan Detection
Another effective method is to invert the BGR image, convert it to HSV, and isolate the cyan color (complementary to red). This eliminates the need for checking multiple hue ranges.
Code for Cyan Detection:
# Invert the BGR image inverted = 255 - image # Convert to HSV color space hsv_inverted = cv2.cvtColor(inverted, cv2.COLOR_BGR2HSV) # Isolate cyan color cyan_mask = cv2.inRange(hsv_inverted, (90-10, S_MIN, V_MIN), (90+10, S_MAX, V_MAX)) # Display the cyan mask cv2.imshow('Cyan Mask', cyan_mask) cv2.waitKey(0)
The above is the detailed content of How can we enhance red color detection in OpenCV using HSV color space?. For more information, please follow other related articles on the PHP Chinese website!