查找最大轮廓OpenCV [英] Find largest contours OpenCV

查看:469
本文介绍了查找最大轮廓OpenCV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了canny边缘检测,并且在要处理的图像上发现了轮廓。
我想找到五个最大轮廓,然后查看图像中五个最大轮廓内是否有轮廓。
这可能吗?我是OpenCV的新手。

I have used canny edge detection and I have found the contours on an image I am trying to process. I want to find the five largest contours and then see whether or not there are contours within the five biggest contours in the image. Is this possible? I am new to OpenCV.

推荐答案

您可以找到最大的 N 轮廓检查其长度。您应该注意将参数 CHAIN_APPROX_NONE 传递给 findContours ,以使其正常工作。

You can find the N largest contours checking their length. You should take care to pass to findContours the parameter CHAIN_APPROX_NONE for this to work properly.

然后可以检查每个蒙版内部是否有其他轮廓。

You can then check inside each mask if there are other contours.

图片:

N = 5 最大轮廓,带有内部每个轮廓。

N = 5 largest contours, with inner contours for each one.

代码:

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

这篇关于查找最大轮廓OpenCV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆