opencv轮廓区域返回零

时间:2014-01-29 21:52:04

标签: c++ opencv contour

我正在学习opencv,使用同名的书。我想计算轮廓的面积,但它总是返回0.轮廓被绘制成闭合的多边形,所以这似乎是正确的。

有一些样本,但他们正在使用vector<vector<Point>> contours。我的下面的代码基于书籍样本。我正在使用的参考图像是grayscale

所以我的问题是:我错过了什么来获得该区域!= 0?

#include <opencv\cv.h>
#include <opencv\highgui.h>

#define CVX_RED CV_RGB(0xff,0x00,0x00)
#define CVX_BLUE CV_RGB(0x00,0x00,0xff)

int main(int argc, char* argv[]) {

 cvNamedWindow( argv[0], 1 );

IplImage* img_8uc1 = cvLoadImage( argv[1], CV_LOAD_IMAGE_GRAYSCALE );
IplImage* img_edge = cvCreateImage( cvGetSize(img_8uc1), 8, 1 );
IplImage* img_8uc3 = cvCreateImage( cvGetSize(img_8uc1), 8, 3 );

cvThreshold( img_8uc1, img_edge, 128, 255, CV_THRESH_BINARY );
CvMemStorage* storage = cvCreateMemStorage();

CvSeq* contours = NULL;
int num_contours = cvFindContours(img_edge, storage, &contours, sizeof(CvContour),
    CV_RETR_LIST, CV_CHAIN_APPROX_NONE, cvPoint(0, 0));
printf("Total Contours Detected: %d\n", num_contours );

int n=0;
for(CvSeq* current_contour = contours; current_contour != NULL;  current_contour=current_contour->h_next ) {

    printf("Contour #%d\n", n);
    int point_cnt = current_contour->total;
    printf(" %d elements\n", point_cnt );

    if(point_cnt < 20){
        continue;
    }

    double area = fabs(cvContourArea(current_contour, CV_WHOLE_SEQ, 0));
    printf(" area: %d\n", area );

    cvCvtColor(img_8uc1, img_8uc3, CV_GRAY2BGR);
    cvDrawContours(img_8uc3, current_contour, CVX_RED, CVX_BLUE, 0, 2, 8);

    cvShowImage(argv[0], img_8uc3);

    cvWaitKey(0);
    n++;
 }

 printf("Finished contours.\n");

 cvCvtColor( img_8uc1, img_8uc3, CV_GRAY2BGR );

 cvShowImage( argv[0], img_8uc3 );
 cvWaitKey(0);
 cvDestroyWindow( argv[0] );
     cvReleaseImage( &img_8uc1 );
 cvReleaseImage( &img_8uc3 );
 cvReleaseImage( &img_edge );

 return 0;
}

1 个答案:

答案 0 :(得分:3)

这不是因为'area'是0而是因为你使用带有标志%d(整数)而不是%f(double)的printf。如果使用适当的标志,您将看到“区域”的实际值。出于这个原因,我总是使用cout而不是printf。这节省了很多这类问题。

旁注。您正在这里学习OpenCV的C接口。我建议你学习它的C ++接口(它从2.0版开始就被添加到OpenCV中)。首先,不推荐使用C接口,并且很可能会从下一版本的OpenCV中完全删除它。其次,它比C ++接口更复杂。在cvFindContours的情况下,它更复杂。 Here您可以找到所有接口所需的文档。

相关问题