C++ OpenCV 更好地检测红色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32522989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
OpenCV better detection of red color?
提问by kav
I have the following image:
我有以下图片:
I would like to detect the red rectangle using cv::inRange
method and HSV color space.
我想使用cv::inRange
方法和 HSV 颜色空间检测红色矩形。
int H_MIN = 0;
int H_MAX = 10;
int S_MIN = 70;
int S_MAX = 255;
int V_MIN = 50;
int V_MAX = 255;
cv::cvtColor( input, imageHSV, cv::COLOR_BGR2HSV );
cv::inRange( imageHSV, cv::Scalar( H_MIN, S_MIN, V_MIN ), cv::Scalar( H_MAX, S_MAX, V_MAX ), imgThreshold0 );
I already created dynamic trackbars in order to change the values for HSV, but I can't get the desired result.
我已经创建了动态轨迹栏以更改 HSV 的值,但我无法获得所需的结果。
Any suggestion for best values (and maybe filters) to use?
对最佳值(可能还有过滤器)的使用有什么建议吗?
回答by Miki
In HSV space, the red color wrapsaround 180. So you need the H
values to be both in [0,10] and [170, 180].
在HSV空间,红色包裹所以你需要周围180H
值既在[0,10]和[170,180]。
Try this:
尝试这个:
#include <opencv2\opencv.hpp>
using namespace cv;
int main()
{
Mat3b bgr = imread("path_to_image");
Mat3b hsv;
cvtColor(bgr, hsv, COLOR_BGR2HSV);
Mat1b mask1, mask2;
inRange(hsv, Scalar(0, 70, 50), Scalar(10, 255, 255), mask1);
inRange(hsv, Scalar(170, 70, 50), Scalar(180, 255, 255), mask2);
Mat1b mask = mask1 | mask2;
imshow("Mask", mask);
waitKey();
return 0;
}
Your previous result:
您之前的结果:
Result adding range [170, 180]:
结果添加范围[170, 180]:
Another interesting approach which needs to check a single range only is:
另一种只需要检查单个范围的有趣方法是:
- invert the BGR image
- convert to HSV
- look for cyancolor
- 反转 BGR 图像
- 转换为 HSV
- 找青色颜色
This idea has been proposed by fmw42and kindly pointed out by Mark Setchell. Thank you very much for that.
这个想法是由fmw42提出的,并被Mark Setchell亲切地指出。非常感谢你。
#include <opencv2\opencv.hpp>
using namespace cv;
int main()
{
Mat3b bgr = imread("path_to_image");
Mat3b bgr_inv = ~bgr;
Mat3b hsv_inv;
cvtColor(bgr_inv, hsv_inv, COLOR_BGR2HSV);
Mat1b mask;
inRange(hsv_inv, Scalar(90 - 10, 70, 50), Scalar(90 + 10, 255, 255), mask); // Cyan is 90
imshow("Mask", mask);
waitKey();
return 0;
}