在OpenCV中获取轮廓的坐标

3

假设我有以下输出图像:

enter image description here

我有一个视频流,想要在输出图像中获取矩形的坐标。这是我的C++代码:

while(1)
    {
        capture >> frame;

        if(frame.empty())
            break;

        cv::cvtColor( frame, gray, CV_BGR2GRAY ); // Grayscale image

        Canny( gray, canny_output, thresh, thresh * 2, 3 );

        // Find contours
        findContours( canny_output, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );

        // Draw contours
        Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 );

        for( int i = 0; i< contours.size(); i++ )
        {
            Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
            drawContours( drawing, contours, i, color, 2, 8, hierarchy, 0, Point() );
        }

        cv::imshow( "w", drawing );

        waitKey(20); // waits to display frame

    }

感谢您的选择。

请注意,您的矩形被分成了2或3个轮廓(因为它们有不同的颜色)。看起来您的输入材料不够好(例如边缘图像中的微小孔洞或其他问题)。 - Micka
2个回答

3

查看OpenCV文档中findContours函数的定义并查看参数(链接):

void findContours(InputOutputArray image, OutputArrayOfArrays contours, OutputArray hierarchy, int mode, int method, Point offset=Point())

参数: 这里

看轮廓,就像Rafa所说的那样,每个轮廓都存储在点的向量中,并且每个点的向量都存储在一个大的向量中,因此,通过遍历外部向量,然后遍历内部向量,您将找到所需的点。

但是,如果您只想检测更大的轮廓,则可以使用CV_RETR_EXTERNAL作为模式参数,因为它将仅检测最外部轮廓(大矩形)。

如果您仍然希望保留较小的轮廓,则可以使用CV_RETR_TREE并使用层次结构进行处理:使用层次结构轮廓


2
查看文档OutputArrayOfArrays轮廓是关键。

轮廓-contours.检测到的轮廓。每个轮廓都存储为点的向量。

因此,您得到了一个vector< vector<Point> > contours。内部的vector<Point>是轮廓的坐标,每个轮廓都存储在一个vector中。

例如,要查看第5个向量,它是vector<Point> fifthcontour = contours.at(4);

然后您就可以在该向量中访问这些坐标。

您可以通过以下方式访问这些坐标:

for (int i = 0; i < fifthcontour.size(); i++) {
    Point coordinate_i_ofcontour = fifthcontour[i];
    cout << endl << "contour with coordinates: x = " << coordinate_i_ofcontour.x << " y = " << coordinate_i_ofcontour.y;
}

这应该是 Point coordinate_i_ofcontour = fifthcontour[i]; 吧? - user1676300

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接