cvFindContours可以从二值图像中检索轮廓,并返回检测到的轮廓的个数。first_contour的值由函数填充返回,它的值将为第一个外轮廓的指针,当没有轮廓被检测到时为NULL。其它轮廓可以使用h_next和v_next连接,从first_contour到达。
[cpp] view plaincopy int cvFindContours( CvArr* image, CvMemStorage* storage, CvSeq** first_contour, int header_size=sizeof(CvContour), int mode=CV_RETR_LIST, int method=CV_CHAIN_APPROX_SIMPLE, CvPoint offset=cvPoint(0,0) );
[cpp] view plaincopy #include <stdio.h> #include <cv.h> #include <cxcore.h> #include <highgui.h> #pragma comment(lib, "cv.lib") #pragma comment(lib, "cxcore.lib") #pragma comment(lib, "highgui.lib") int main( int argc, char** argv ) { // 以灰度值读取图片 IplImage* pImg = cvLoadImage(".\\test.png", 0); IplImage* pContourImg = NULL; CvMemStorage * storage = cvCreateMemStorage(0); CvSeq *contour = 0, *contmax = 0; int mode = CV_RETR_EXTERNAL; cvNamedWindow("src", 0); cvShowImage( "src", pImg ); // 为轮廓显示图像申请空间, 3通道图像,以便用彩色显示 pContourImg = cvCreateImage(cvGetSize(pImg), IPL_DEPTH_8U, 3); // copy source image and convert it to BGR image cvCvtColor(pImg, pContourImg, CV_GRAY2BGR); // 查找contour int nContours = cvFindContours( pImg, storage, &contour, sizeof(CvContour), mode, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0)); // 将轮廓画出 cvDrawContours(pContourImg, contour, CV_RGB(255,0,0), CV_RGB(255, 0, 0), 2, 2, 8, cvPoint(0,0)); double area, maxArea = 10; //设面积最大值大于10Pixel for( ; contour; contour = contour->h_next) { area = fabs(cvContourArea(contour, CV_WHOLE_SEQ)); //获取当前轮廓面积 printf("area == %lf\n", area); if(area > maxArea) { contmax = contour; maxArea = area; } } CvRect aRect = cvBoundingRect(contmax, 0); cvSetImageROI(pContourImg, aRect); // 显示图像 cvNamedWindow("contour", 0); cvShowImage("contour", pContourImg); cvWaitKey(-1); // 销毁窗口 cvDestroyWindow("src"); cvDestroyWindow("contour"); // 释放图像 cvReleaseImage(&pImg); cvReleaseImage(&pContourImg); cvClearMemStorage(storage); cvReleaseMemStorage(&storage); return 0; }