簡體   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