1. 程式人生 > >OpenCV畫輪廓的外界圓矩形橢圓等

OpenCV畫輪廓的外界圓矩形橢圓等

               
#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);    }