#include <cv.h> #include <cxcore.h> #include <highgui.h> #include <iostream> using namespace std; #pragma comment(lib,"cv.lib") #pragma comment(lib,"highgui.lib") #pragma comment(lib,"cxcore.lib") int main() { IplImage *src = cvLoadImage("D:\\三值canny的圖.bmp",0); //IplImage *src = cvLoadImage("D:\\BoardStereoL3.jpg",0); CvMemStorage *storage = cvCreateMemStorage(); //建立一個內存區域,該區域是額能夠動態增加的 CvSeq *seq = NULL; //定義一個序列,這些序列能夠存放在上面的內存區域裏 int cnt = cvFindContours(src,storage,&seq,sizeof(CvContour),2);// // //默認:mode=CV_RETR_LIST,檢索所偶輪廓 seq = seq->v_next; int c=seq->total;//當前輪廓包含多少個元素,這裏的元素爲點 double length = cvArcLength(seq); //獲得指定的那個輪廓的周長 //該函數有3個參數:序列,起點(默認計算整條曲線),是否封閉曲線 double area = cvContourArea(seq); //獲得指定的那個輪廓的面積 CvRect rect = cvBoundingRect(seq,1); //根據序列,返回輪廓外圍矩形; CvBox2D box = cvMinAreaRect2(seq,NULL); //最小外圍矩形 cout<<"Length = "<<length<<endl; cout<<"Area = "<<area<<endl; CvPoint pt1,pt2; pt1.x=rect.x; pt1.y=rect.y; pt2.x=rect.x+rect.width; pt2.y=rect.y+rect.height; IplImage *dst = cvCreateImage(cvGetSize(src),8,3); //目標圖像爲3通道圖 cvZero(dst); cvDrawContours(dst,seq,CV_RGB(255,0,0),CV_RGB(255,0,0),0); cvRectangle(dst,pt1,pt2,CV_RGB(0,255,0)); cvNamedWindow("dst",1); cvShowImage("dst",dst); cvWaitKey(); CvPoint2D32f center; float radius; int a= cvMinEnclosingCircle(seq,¢er,&radius); //根據序列畫出最小面積外接圓 cout<<"center.x = "<<center.x<<endl; cout<<"center.y = "<<center.y<<endl; cout<<"radius = "<<radius<<endl; //圓必須是包含全部點,成功返回1,而且獲得圓心和半徑 cvCircle(dst,cvPointFrom32f(center),cvRound(radius),CV_RGB(100,100,100)); cvShowImage("dst",dst); cvWaitKey(); CvBox2D ellipse = cvFitEllipse2(seq);//最小二乘法的橢圓擬合 cvEllipseBox(dst,ellipse,CV_RGB(255,255,0)); //在圖上畫橢圓 cvShowImage("dst",dst); cvWaitKey(); //繪製外接最小矩形 CvPoint2D32f pt[4]; cvBoxPoints(box,pt); for(int i = 0;i<4;++i){ cvLine(dst,cvPointFrom32f(pt[i]),cvPointFrom32f(pt[((i+1)%4)?(i+1):0]),CV_RGB(0,0,255)); } cvShowImage("dst",dst); cvWaitKey(); cvReleaseImage(&src); cvReleaseImage(&dst); cvReleaseMemStorage(&storage); }