OpenCV cvFindContours只找到一个轮廓

时间:2012-08-07 18:21:17

标签: c opencv computer-vision contour feature-detection

我继续使用openCV工作,这是我描述的第一次冒险here。它进展顺利,但我偶然发现了另一件棘手的事情。我想在图像上找到轮廓,我已将自适应阈值应用于:

enter image description here

所以cvFindContours似乎工作得很好,结果如下:

enter image description here

问题是,当我尝试迭代找到的countours时,它说只有一个轮廓(以下代码中的contours->total等于1)。这是代码:

IplImage* img;
if((img = cvLoadImage( "photos/img-000012.ppm", 1)) == 0 )
{
    perror("cvLoadImage");
    return 1;
}
cvNamedWindow( "Image view", 1 );
cvShowImage( "Image view", img );

IplImage* gray = cvCreateImage( cvGetSize(img), 8, 1 ); // allocate a 1 channel byte image
cvCvtColor( img, gray, CV_BGR2GRAY );
cvShowImage( "Image view", gray );
cvWaitKey(0);

cvAdaptiveThreshold(gray, gray,
        255,    //  Non-zero value assigned to the pixels for which the condition is satisfied
        CV_ADAPTIVE_THRESH_MEAN_C, // adaptiveMethod
        CV_THRESH_BINARY_INV,   // thresholdType
        11, // blockSize
        5); // Constant subtracted from the mean or weighted mean
cvShowImage( "Image view", gray );
cvWaitKey(0);

IplConvKernel *se = cvCreateStructuringElementEx(3, 3, 1,  1,  CV_SHAPE_RECT, NULL);
cvErode(gray, gray, se, 1);
cvShowImage( "Image view", gray );
cvWaitKey(0);

IplImage *canny_out = cvCreateImage(cvGetSize(gray), 8, 1);
cvCanny(gray, canny_out, 50, 100, 3);
cvShowImage( "Image view", canny_out );
cvWaitKey(0);

CvMemStorage *storage = cvCreateMemStorage(0);
CvSeq *contours = cvCreateSeq(0, sizeof(CvSeq), sizeof(CvPoint), storage);
cvFindContours(gray, storage, &contours, sizeof(CvContour), CV_RETR_LIST,
        CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));
printf("contours->total = %d\n", contours->total);

cvDrawContours(img, contours, CV_RGB(0,255,0), CV_RGB(0,0,255),
        2, 1, 8, cvPoint(0, 0));
cvShowImage( "Image view", img );
cvWaitKey(0);

是不是这样,只有一个轮廓?也许我不了解openCV对轮廓的定义?我很感激你的帮助。

2 个答案:

答案 0 :(得分:2)

实际上cvFindContours会返回已创建轮廓的数量(我测试了您的图片并返回> 1)。见docs。但我不知道为什么total等于一个。

答案 1 :(得分:0)

  1. cvCreateSeq()
  2. 之前您不需要cvFindContours()
  3. 而不是contours-> total,遍历它们。

    for (; contours != 0; contours = contours->h_next)