OpenCV 更好地检测红色?

OpenCV better detection of red color?(OpenCV 更好地检测红色?)

本文介绍了OpenCV 更好地检测红色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下图片:

我想使用 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(输入,imageHSV,cv::COLOR_BGR2HSV);cv::inRange(imageHSV, cv::Scalar(H_MIN, S_MIN, V_MIN), cv::Scalar(H_MAX, S_MAX, V_MAX), imgThreshold0);

我已经创建了动态轨迹栏以更改 HSV 的值,但我无法获得所需的结果.

对使用的最佳值(可能还有过滤器)有什么建议吗?

解决方案

在 HSV 空间中,红色环绕大约 180.所以你需要 H 值在 [0,10] 和 [170, 180] 中.

试试这个:

#include 使用命名空间 cv;int main(){Mat3b bgr = imread("path_to_image");Mat3b hsv;cvtColor(bgr, hsv, COLOR_BGR2HSV);Mat1b 掩码1、掩码2;inRange(hsv, Scalar(0, 70, 50), Scalar(10, 255, 255), mask1);inRange(hsv, Scalar(170, 70, 50), Scalar(180, 255, 255), mask2);Mat1b 掩码 = 掩码 1 |面具2;imshow("面具", 面具);等待键();返回0;}

您之前的结果:

结果添加范围[170, 180]:

<小时>

另一种只需要检查单个范围的有趣方法是:

  • 反转 BGR 图像
  • 转换为 HSV
  • 寻找青色颜色

这个想法由

I have the following image:

I would like to detect the red rectangle using cv::inRange method and HSV color space.

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.

Any suggestion for best values (and maybe filters) to use?

解决方案

In HSV space, the red color wraps around 180. So you need the H values to be both in [0,10] and [170, 180].

Try this:

#include <opencv2opencv.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]:


Another interesting approach which needs to check a single range only is:

  • invert the BGR image
  • convert to HSV
  • look for cyan color

This idea has been proposed by fmw42 and kindly pointed out by Mark Setchell. Thank you very much for that.

#include <opencv2opencv.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;
}

这篇关于OpenCV 更好地检测红色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:OpenCV 更好地检测红色?

基础教程推荐