Hai
cvFindContours(binaryim, contourStorage, &contourSeq, sizeof(CvContour),CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, cvPoint(0, 0));
&contourSeq是用于储存轮廓的序列
contourSeq->total 所表示的是contourSeq 当前指针所指向轮廓 所包含像素点的数目而非轮廓总数
采用如下放下计数轮廓数量:
for(;contourSeq!=0;contourSeq=contourSeq->h_next)
{
contourcount++;
}
printf("contour count is %d",contourcount);
可直接运行代码如下:
1 #include "cv.h" 2 #include "highgui.h" 3 #include <stdio.h> 4 #include <math.h> 5 #include <iostream> 6 #include <ctime> 7 using namespace cv; 8 CvSeq *contourSeq = NULL; 9 10 IplImage* ImageThreshold(IplImage* src) 11 { 12 IplImage *gray,*binaryim; 13 int height,width; 14 gray=cvCreateImage(cvGetSize(src),src->depth,1); 15 cvCvtColor(src,gray,CV_BGR2GRAY); 16 height=gray->height; 17 width=gray->width; 18 printf("The canvas'width is :%d, height is :%d\n\n",width,height); 19 20 binaryim=cvCreateImage(cvGetSize(src),IPL_DEPTH_8U,1); 21 cvThreshold(gray,binaryim,128,255,CV_THRESH_BINARY_INV); 22 return binaryim; 23 24 } 25 26 IplImage* printlunkuo(IplImage *binaryim) 27 { 28 CvMemStorage *contourStorage=cvCreateMemStorage(); 29 cvFindContours(binaryim, contourStorage, &contourSeq, sizeof(CvContour),CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, cvPoint(0, 0)); 30 31 IplImage *pOutlineImage = cvCreateImage(cvGetSize(binaryim), IPL_DEPTH_8U, 3); 32 int nLevels = 5; 33 cvRectangle(pOutlineImage,cvPoint(0,0),cvPoint(pOutlineImage->height,pOutlineImage->width),CV_RGB(0,0,0),CV_FILLED); 34 cvDrawContours(pOutlineImage, contourSeq, CV_RGB(255,0,0), CV_RGB(0,255,0), nLevels,0.5); 35 36 int contourcount=0; 37 for(;contourSeq!=0;contourSeq=contourSeq->h_next) 38 { 39 contourcount++; 40 } 41 printf("contour count is %d",contourcount); 42 43 44 45 return pOutlineImage; 46 47 48 49 } 50 51 52 int main(int argc,char** argv) 53 { 54 IplImage *src,*binaryim,*contourim; 55 src=cvLoadImage("gtest2.bmp",1); 56 binaryim=ImageThreshold(src); 57 contourim = printlunkuo(binaryim); 58 59 60 cvSaveImage("save.bmp", contourim); 61 62 63 64 65 66 67 68 cvNamedWindow("Binary_image",0); 69 cvShowImage("Binary_image",binaryim); 70 cvNamedWindow("Contour_image",0); 71 cvShowImage("Contour_image",contourim); 72 cvWaitKey(0); 73 74 cvDestroyWindow("Binary_image"); 75 cvReleaseImage(&binaryim); 76 cvDestroyWindow("Contours_image"); 77 cvReleaseImage(&contourim); 78 79 80 }