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