繁体   English   中英

OpenCV:如何解释inRange的结果?

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

我正在处理视频图像,我想检测视频是否包含一定范围红色的像素。 这可能吗?

这是我从教程改编的代码:

#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
}

解释值

我想检测inRange操作的结果是否为nil。 换句话说,我想了解原始图像中是否有匹配的像素,其颜色分别来自给定的上下红色刻度。 如何解释结果?

首先,您需要对上下遮罩进行“或”运算:

Mat mask = lower_red_hue_range | upper_red_hue_range;

然后,您可以countNonZero以查看是否存在非零像素(即,您找到了什么)。

int number_of_non_zero_pixels = countNonZero(mask);

最好先进行形态学侵蚀或张开以去除较小的(可能是嘈杂的)斑​​点:

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

或查找连接的组件( 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