簡體   English   中英

查找最大輪廓OpenCV

[英]Find largest contours OpenCV

我使用了Canny邊緣檢測,並且在要處理的圖像上發現了輪廓。 我想找到五個最大輪廓,然后查看圖像中五個最大輪廓內是否有輪廓。 這可能嗎? 我是OpenCV的新手。

您可以找到N最大的輪廓來檢查它們的長度。 您應該注意將參數CHAIN_APPROX_NONE傳遞給findContours ,以使其正常工作。

然后,您可以檢查每個蒙版內部是否有其他輪廓。

圖片:

在此處輸入圖片說明

N = 5最大輪廓,每個輪廓都有內部輪廓。

在此處輸入圖片說明

碼:

#include <opencv2\opencv.hpp>
#include <vector>
#include <numeric>
using namespace cv;
using namespace std;


int main()
{
    Mat3b img = imread("path_to_image");

    Mat1b gray;
    cvtColor(img, gray, COLOR_BGR2GRAY);

    Mat1b edges;
    Canny(gray, edges, 200, 50);

    vector<vector<Point>> contours;
    findContours(edges.clone(), contours, RETR_EXTERNAL, CHAIN_APPROX_NONE);

    vector<int> indices(contours.size());
    iota(indices.begin(), indices.end(), 0);

    sort(indices.begin(), indices.end(), [&contours](int lhs, int rhs) {
        return contours[lhs].size() > contours[rhs].size();
    });

    int N = 5; // set number of largest contours
    N = min(N, int(contours.size()));

    Mat3b res = img.clone();

    // Draw N largest contours
    for (int i = 0; i < N; ++i)
    {
        Scalar color(rand() & 255, rand() & 255, rand() & 255);
        Vec3b otherColor(color[2], color[0], color[1]);

        drawContours(res, contours, indices[i], color, CV_FILLED);

        // Create a mask for the contour
        Mat1b res_mask(img.rows, img.cols, uchar(0));
        drawContours(res_mask, contours, indices[i], Scalar(255), CV_FILLED);

        // AND with edges
        res_mask &= edges;

        // remove larger contours
        drawContours(res_mask, contours, indices[i], Scalar(0), 2);

        for (int r = 0; r < img.rows; ++r)
        {
            for (int c = 0; c < img.cols; ++c)
            {
                if (res_mask(r, c))
                {
                    res(r,c) = otherColor;
                }
            }
        }
    }

    imshow("Image", img);
    imshow("N largest contours", res);
    waitKey();

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM