Choosing the Correct Upper and Lower HSV Boundaries for Color Detection with cv::inRange (OpenCV)
When detecting colors in images using the cv::inRange function in OpenCV, it is crucial to select appropriate upper and lower boundaries for the HSV (Hue, Saturation, Value) color space. This ensures accurate color detection and allows for efficient segmentation.
Problem:
Consider an image containing an orange lid on a coffee can. The HSV value at the center of the lid, obtained using the gcolor2 utility, is (22, 59, 100). Using initial boundaries defined as min = (18, 40, 90) and max = (27, 255, 255) resulted in unexpected detection results.
Solution:
Problem 1: HSV Range Variation
Different applications often use different scales for HSV values. GIMP, for example, employs a scale of H: 0-360, S: 0-100, V: 0-100, while OpenCV uses H: 0-179, S: 0-255, V: 0-255. In this case, the hue value of 22 in GIMP should be converted to 11 in OpenCV by taking half its value. Thus, the revised boundary becomes (5, 50, 50) - (15, 255, 255).
Problem 2: Color Space Compatibility
OpenCV employs the BGR (Blue-Green-Red) color format, not RGB. To ensure compatibility, the code converting RGB to HSV should be modified to:
cv.CvtColor(frame, frameHSV, cv.CV_BGR2HSV)
Updated Code:
import cv in_image = 'kaffee.png' out_image = 'kaffee_out.png' out_image_thr = 'kaffee_thr.png' ORANGE_MIN = cv.Scalar(5, 50, 50) ORANGE_MAX = cv.Scalar(15, 255, 255) COLOR_MIN = ORANGE_MIN COLOR_MAX = ORANGE_MAX def test1(): frame = cv.LoadImage(in_image) frameHSV = cv.CreateImage(cv.GetSize(frame), 8, 3) cv.CvtColor(frame, frameHSV, cv.CV_BGR2HSV) frame_threshed = cv.CreateImage(cv.GetSize(frameHSV), 8, 1) cv.InRangeS(frameHSV, COLOR_MIN, COLOR_MAX, frame_threshed) cv.SaveImage(out_image_thr, frame_threshed) if __name__ == '__main__': test1()
Result:
Running the updated code yields a more accurate segmentation of the orange lid.
Note:
There may be some small false detections due to similar hues in the background. To address this, further processing such as contour analysis can be applied to isolate the largest contour corresponding to the lid.
The above is the detailed content of How to Choose the Correct HSV Upper and Lower Boundaries for Accurate Color Detection in OpenCV?. For more information, please follow other related articles on the PHP Chinese website!