OpenCV findContours 破坏源图像

3
我正在编写一段代码,用于在单通道空白图像中绘制圆、线和矩形。之后,我发现在图像中找到了所有的轮廓,但在找到轮廓后,我的源图像变得扭曲了。为什么会出现这种情况?有人能帮我解决吗?以下是我的代码。
using namespace cv;
using namespace std;
int main()
{

    Mat dst = Mat::zeros(480, 480, CV_8UC1);
    Mat draw= Mat::zeros(480, 480, CV_8UC1);

    line(draw, Point(100,100), Point(150,150), Scalar(255,0,0),1,8,0);
    rectangle(draw, Rect(200,300,10,15),  Scalar(255,0,0),1, 8,0); 
    circle(draw, Point(80,80),20, Scalar(255,0,0),1,8,0);

    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;

    findContours( draw, contours, hierarchy,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );

     for( int i = 0; i< contours.size(); i++ )
    {
        Scalar color( 255,255,255);
        drawContours( dst, contours, i, color, 1, 8, hierarchy );
    }

    imshow( "Components", dst );
    imshow( "draw", draw );

    waitKey(0);
}

源图像

enter image description here

找到轮廓后的扭曲源图像


第一张图片是未失真的源图像吗? - Animesh Pandey
不,这是drawContours函数后的图像。但它与原始图像相同。 - Haris
4个回答

12

1
对于那些在复制图像时遇到困难的人,请尝试使用以下代码:cv::Mat imageCopy = image.clone(); - Johann Burgess

2

尝试使用findContours( draw.clone(), contours, hierarchy,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );


1
我认为问题在于您期望从findContours得到一个完美的图形,但它给您提供了一张丑陋的图像。FindContours不会给出您所需图形的精确轮廓。您必须使用drawContours函数才能生成正确的图像。请参考这里的参考文献:http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontours#findcontours。您可以看到第一个参数是输入/输出数组。因此,该函数使用相同的数组来打开、修改和保存图像。这就是为什么您会得到一个扭曲的图像。另外,请查看参数说明。当它谈论第一个参数时,它说:“提取轮廓时,该函数修改了图像。”我没有大量使用findContours,但我从未获得过我想要的清晰图像。我必须始终使用drawContours才能得到漂亮的图形。否则,您可以使用Canny函数,它将给您边缘而不是轮廓。

不,我得到了完美的结果,但是在轮廓查找后源图像变形了。 - Haris
1
请记住,在使用findContours函数后,您将无法查看原始图像。FindContours会用其结果覆盖图像。因此,您看到的是轮廓而不是原始图像,而这些轮廓并不是完美的图像。 - enric.cornella

1

对我来说,第二个图像看起来像是边缘检测算法的结果。我猜测findContours函数会用找到的结果覆盖原始图像。

这里查看。


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