Introduction
When dealing with the detection of red color using OpenCV and HSV color space, it can be challenging to obtain satisfactory results. However, by exploring various approaches and parameter adjustments, significant improvements can be made.
Problem
To enhance the detection of a red rectangle within an image, the following code has been utilized:
#include <opencv2/opencv.hpp> int main() { // Image initialization Mat input = imread("path_to_image"); // HSV conversion Mat imageHSV; cvtColor(input, imageHSV, COLOR_BGR2HSV); // HSV parameter ranges int H_MIN = 0; int H_MAX = 10; int S_MIN = 70; int S_MAX = 255; int V_MIN = 50; int V_MAX = 255; // Red color range in HSV cv::inRange(imageHSV, cv::Scalar(H_MIN, S_MIN, V_MIN), cv::Scalar(H_MAX, S_MAX, V_MAX), imgThreshold0); }
Despite adjusting the HSV values using dynamic trackbars, optimal results remain elusive.
Solutions
1. Expanding Hue Value Range:
In HSV space, the red color wraps around 180. Therefore, to fully capture the entire range of red, the hue value (H) must consider both [0,10] and [170, 180].
inRange(hsv, Scalar(0, 70, 50), Scalar(10, 255, 255), mask1); inRange(hsv, Scalar(170, 70, 50), Scalar(180, 255, 255), mask2);
2. Inverting Image and Detecting Cyan:
Alternatively, an intriguing approach is to:
This method effectively detects the complement of red (cyan) with only a single range in HSV.
// Invert original image Mat3b bgr_inv = ~bgr; // Convert to HSV Mat3b hsv_inv; cvtColor(bgr_inv, hsv_inv, COLOR_BGR2HSV); // Detect cyan range inRange(hsv_inv, Scalar(90 - 10, 70, 50), Scalar(90 + 10, 255, 255), mask);
Conclusion
By incorporating these enhanced techniques, OpenCV can effectively detect red color with greater precision. These approaches provide a solid foundation for further optimizations and applications in various image processing scenarios.
The above is the detailed content of How can I improve red color detection in OpenCV using HSV color space?. For more information, please follow other related articles on the PHP Chinese website!