为什么在opencv中FindContours函数找到两个轮廓而不是图像中的一个如下所示?

时间:2011-09-02 20:02:07

标签: c opencv

输入图片 - http://i.imgur.com/sLoqh.png 带有凸轮廓的输出图像绘制轮廓 - http://i.imgur.com/AaNJY.png

对于如何获得一个轮廓的任何帮助都将非常感激?

1 个答案:

答案 0 :(得分:2)

将图像检索为一个轮廓的技巧似乎是在执行Canny之前使用cvFindContours处理图像。

IplImage* src = cvLoadImage(argv[1], CV_LOAD_IMAGE_GRAYSCALE);

IplImage* cc_img = cvCreateImage( cvGetSize(src), src->depth, 3 );
cvSetZero(cc_img);
CvScalar(ext_color);

CvMemStorage *mem;
mem = cvCreateMemStorage(0);
CvSeq *contours = 0;

// edges returned by Canny might have small gaps between them, which causes some problems during contour detection
// Simplest way to solve this s to "dilate" the image.
cvCanny(src, src, 10, 50, 3); 
cvShowImage("Tutorial", src);
cvWaitKey(0);

int n = cvFindContours( src, mem, &contours, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));

CvSeq* ptr = 0;
for (ptr = contours; ptr != NULL; ptr = ptr->h_next)
{   
    ext_color = CV_RGB( rand()&255, rand()&255, rand()&255 ); //randomly coloring different contours
    cvDrawContours(cc_img, ptr, ext_color, CV_RGB(0,0,0), -1, CV_FILLED, 8, cvPoint(0,0));
}   

cvNamedWindow("Tutorial");
cvShowImage("Tutorial", cc_img);
//cvSaveImage("out.png", cc_img);

cvWaitKey(0);

输出:

enter image description here

相关问题