OpenCv findcontours()太多轮廓

Kri*_*rov 2 c++ opencv

我的形状我想从中提取轮廓(我需要正确的轮廓数量 - 两个),但在层次结构中我得到4个或更多而不是两个轮廓.我只是无法意识到为什么,这是显而易见的,没有噪音,我以前曾使用过困境和侵蚀.

在findcontours()之前

在findcontours()之后

我试图更改所有参数,什么都没有.我也尝试了白色方块的图像,并没有工作.有我的界限:

Mat I = imread("test.png", CV_LOAD_IMAGE_GRAYSCALE);
I.convertTo(B, CV_8U);    
findContours(B, contour_vec, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_NONE);
Run Code Online (Sandbox Code Playgroud)

为什么轮廓如此断开?如何在层次结构中创建2个轮廓?

Mik*_*iki 7

在您的图像中有5个轮廓:2个外部轮廓,2个内部轮廓和1个右上角.

您可以丢弃内部和外部轮廓,看它们是CW还是CCW.您可以使用带有面向标志的contourArea来执行此操作:

面向导向的区域标志.如果为true,则该函数返回有符号区域值,具体取决于轮廓方向(顺时针或逆时针).使用此功能,您可以通过拍摄区域的符号来确定轮廓的方向.默认情况下,参数为false,表示返回绝对值.

因此,绘制外部轮廓为红色,内部为绿色,您会得到:

在此输入图像描述

然后,您只能externalContours在下面的代码中存储外部轮廓(请参阅参考资料):

#include <opencv2\opencv.hpp>
#include <vector>

using namespace std;
using namespace cv;

int main()
{
    // Load grayscale image
    Mat1b B = imread("path_to_image", IMREAD_GRAYSCALE);

    // Find contours
    vector<vector<Point>> contours;
    findContours(B.clone(), contours, RETR_TREE, CHAIN_APPROX_NONE);

    // Create output image
    Mat3b out;
    cvtColor(B, out, COLOR_GRAY2BGR);

    vector<vector<Point>> externalContours;
    for (size_t i=0; i<contours.size(); ++i)
    {
        // Find orientation: CW or CCW
        double area = contourArea(contours[i], true);

        if (area >= 0) 
        {
            // Internal contours
            drawContours(out, contours, i, Scalar(0, 255, 0));
        }
        else
        {
            // External contours
            drawContours(out, contours, i, Scalar(0, 0, 255));

            // Save external contours
            externalContours.push_back(contours[i]);
        }
    }

    imshow("Out", out);
    waitKey();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

请记住,findContours破坏输入图像(您显示的第二个图像是垃圾).只需传递图像的克隆,findContours以避免损坏原始图像.