OpenCV Countour区域返回零

opencv countour area returns zero

本文关键字:返回 区域 Countour OpenCV      更新时间:2023-10-16

我通过使用具有相同名称的书来学习OpenCV。我想计算轮廓的面积,但总是返回0。轮廓被涂成封闭的多边形,所以这似乎是正确的。

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

所以我的问题是:我缺少什么来获得区域!= 0?

#include <opencvcv.h>
#include <opencvhighgui.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: %dn", num_contours );
int n=0;
for(CvSeq* current_contour = contours; current_contour != NULL;  current_contour=current_contour->h_next ) {
    printf("Contour #%dn", n);
    int point_cnt = current_contour->total;
    printf(" %d elementsn", point_cnt );
    if(point_cnt < 20){
        continue;
    }
    double area = fabs(cvContourArea(current_contour, CV_WHOLE_SEQ, 0));
    printf(" area: %dn", 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;
}

这不是因为'区域'为0,而是因为您使用了带有flag%d(整数)的printf而不是%f(double)。如果使用适当的标志,您将看到"区域"的实际值。因此,我总是使用COUT而不是printf。这节省了这种问题。

在旁注。您在这里学习OpenCV的界面。我建议您改用其C 接口(自版本2.0以来已添加到OpenCV)。首先,C接口被弃用,很可能将完全从OpenCV的下一个版本中删除。其次,它比C 接口更为复杂。如果有cvfindContours,则更为复杂。在这里,您可以找到所有接口所需的文档。