简体   繁体   English

OpenCV:如何解释inRange的结果?

[英]OpenCV: how can I interpret the results of inRange?

I am processing video images and I would like to detect if the video contains any pixels of a certain range of red. 我正在处理视频图像,我想检测视频是否包含一定范围红色的像素。 Is this possible? 这可能吗?

Here is the code I am adapting from a tutorial: 这是我从教程改编的代码:

#ifdef __cplusplus
- (void)processImage:(Mat&)image;
{
    cv::Mat orig_image = image.clone();
    cv::medianBlur(image, image, 3);
    cv::Mat hsv_image;
    cv::cvtColor(image, hsv_image, cv::COLOR_BGR2HSV);
    cv::Mat lower_red_hue_range;
    cv::Mat upper_red_hue_range;
    cv::inRange(hsv_image, cv::Scalar(0, 100, 100), cv::Scalar(10, 255, 255), lower_red_hue_range);
    cv::inRange(hsv_image, cv::Scalar(160, 100, 100), cv::Scalar(179, 255, 255), upper_red_hue_range);
    // Interpret values here
}

Interpreting values 解释值

I would like to detect if the results from the inRange operations are nil or not. 我想检测inRange操作的结果是否为nil。 In other words I want to understand if there are any matching pixels in the original image with a colour inRange from the given lower and upper red scale. 换句话说,我想了解原始图像中是否有匹配的像素,其颜色分别来自给定的上下红色刻度。 How can I interpret the results? 如何解释结果?

First you need to OR the lower and upper mask: 首先,您需要对上下遮罩进行“或”运算:

Mat mask = lower_red_hue_range | upper_red_hue_range;

Then you can countNonZero to see if there are non zero pixels (ie you found something). 然后,您可以countNonZero以查看是否存在非零像素(即,您找到了什么)。

int number_of_non_zero_pixels = countNonZero(mask);

It could be better to first apply morphological erosion or opening to remove small (probably noisy) blobs: 最好先进行形态学侵蚀或张开以去除较小的(可能是嘈杂的)斑​​点:

Mat kernel = getStructuringElement(MORPH_ELLIPSE, Size(3, 3));
morphologyEx(mask, mask, MORPH_OPEN, kernel); // or MORPH_ERODE

or find connected components ( findContours , connectedComponentsWithStats ) and prune / search for according to some criteria: 或查找连接的组件( findContoursconnectedComponentsWithStats )并修剪/根据一些条件进行搜索:

vector<vector<Point>> contours
findContours(mask.clone(), contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);

double threshold_on_area = 100.0;
for(int i=0; i<contours.size(); ++i)
{
    double area = countourArea(contours[i]);
    if(area < threshold_on_area)
    {
        // don't consider this contour
        continue;
    } 
    else
    {
        // do something (e.g. drawing a bounding box around the contour)
        Rect box = boundingRect(contours[i]);
        rectangle(hsv_image, box, Scalar(0, 255, 255));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM