#include "stdafx.h" #include "cv.h" #include "highgui.h" int main( int argc, char** argv ) { IplImage* src; src=cvLoadImage("D:/Demo.jpg",CV_LOAD_IMAGE_GRAYSCALE); IplImage* dst = cvCreateImage( cvGetSize(src), 8, 3 ); CvMemStorage* storage = cvCreateMemStorage(0); CvSeq* contour = 0; cvThreshold( src, src,120, 255, CV_THRESH_BINARY );//二值化 cvNamedWindow( "Source", 1 ); cvShowImage( "Source", src ); //提取輪廓 cvFindContours( src, storage, &contour, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE ); cvZero( dst );//清空數組 CvSeq* _contour =contour; double maxarea=0; double minarea=100; int n=-1,m=0;//n爲面積最大輪廓索引,m爲迭代索引 for( ; contour != 0; contour = contour->h_next ) { double tmparea=fabs(cvContourArea(contour)); if(tmparea < minarea) { cvSeqRemove(contour,0); //刪除面積小於設定值的輪廓 continue; } CvRect aRect = cvBoundingRect( contour, 0 ); if ((aRect.width/aRect.height)<1) { cvSeqRemove(contour,0); //刪除寬高比例小於設定值的輪廓 continue; } if(tmparea > maxarea) { maxarea = tmparea; n=m; } m++; // CvScalar color = CV_RGB( rand()&255, rand()&255, rand()&255 );//建立一個色彩值 CvScalar color = CV_RGB( 0, 255,255 ); //max_level 繪製輪廓的最大等級。若是等級爲0,繪製單獨的輪廓。若是爲1,繪製輪廓及在其後的相同的級別下輪廓。 //若是值爲2,全部的輪廓。若是等級爲2,繪製全部同級輪廓及全部低一級輪廓,諸此種種。 //若是值爲負數,函數不繪製同級輪廓,但會升序繪製直到級別爲abs(max_level)-1的子輪廓。 cvDrawContours( dst, contour, color, color, -1, 1, 8 );//繪製外部和內部的輪廓 } contour =_contour; /*int k=0;*/ int count=0; for( ; contour != 0; contour = contour->h_next ) { count++; double tmparea=fabs(cvContourArea(contour)); if (tmparea==maxarea /*k==n*/) { CvScalar color = CV_RGB( 255, 0, 0); cvDrawContours( dst, contour, color, color, -1, 1, 8 ); } /*k++;*/ } printf("The total number of contours is:%d",count); cvNamedWindow( "Components", 1 ); cvShowImage( "Components", dst ); cvWaitKey(0); cvDestroyWindow( "Source" ); cvReleaseImage(&src); cvDestroyWindow( "Components" ); cvReleaseImage(&dst); return 0; }