椭圆拟合

看了网上光宇椭圆拟合的各种算法,都差不多,但是写的条理很乱,借鉴别人的成果,修改了下程序,下边是我梳理后的过程。

#include "cv.h"
#include "highgui.h"
int main()
{   //定义图像
IplImage *img3 = cvLoadImage("spot.JPG",0);
IplImage *img2 = cvCloneImage(img3);
//将原图img3阈值化为img2;
cvThreshold(img3, img2, 50, 255, CV_THRESH_BINARY);
IplImage *img4 = cvCloneImage(img3);
cvNamedWindow("Source", 1);
cvNamedWindow("Result", 1);
cvShowImage("Source", img3);
//设置椭圆拟合用到的几个参数
CvMemStorage *stor = cvCreateMemStorage(0);
CvSeq *cont = cvCreateSeq(CV_SEQ_ELTYPE_POINT, sizeof(CvSeq), sizeof(CvPoint), stor);
CvBox2D32f *box;
CvPoint *PointArray;
CvPoint2D32f *PointArray2D32f;
    //检索椭圆的轮廓,存储在stor
cvFindContours(img2, stor, &cont, sizeof(CvContour),
CV_RETR_LIST, CV_CHAIN_APPROX_NONE, cvPoint(0, 0));
//清空图像img2,img4;
cvZero(img2);
cvZero(img4);
//绘制所有轮廓并用椭圆拟合
for (; cont; cont = cont->h_next)
{
int i;
int count = cont->total;//轮廓个数
CvPoint center;
CvSize size;
/*个数必须大于6,这是cvFitEllipse_32f的要求*/
if (count<6)
{
continue;
}
//分配内存给点集
PointArray = (CvPoint *)malloc(count*sizeof(CvPoint));
PointArray2D32f = (CvPoint2D32f*)malloc(count*sizeof(CvPoint2D32f));
//分配内存给椭圆数据
box = (CvBox2D32f *)malloc(sizeof(CvBox2D32f));
//得到点集(这个方法值得借鉴)
cvCvtSeqToArray(cont, PointArray, CV_WHOLE_SEQ);
//将CvPoint点集转化为CvBox2D32f集合
for (i = 0; i<count; i++)
{
PointArray2D32f[i].x = (float)PointArray[i].x;
PointArray2D32f[i].y = (float)PointArray[i].y;
}
//拟合当前轮廓
cvFitEllipse(PointArray2D32f, count, box);
//绘制当前轮廓
cvDrawContours(img4, cont, CV_RGB(255, 255, 255), CV_RGB(255, 255, 255),
0, 1, 8, cvPoint(0, 0));
//将椭圆数据从浮点转化为整数表示
center.x = cvRound(box->center.x);
center.y = cvRound(box->center.y);
size.width = cvRound(box->size.width*0.5);
size.height = cvRound(box->size.height*0.5);
box->angle = -box->angle;
//画椭圆
cvEllipse(img4, center, size, box->angle, 0, 360, CV_RGB(0, 0, 255), 1, CV_AA, 0);
free(PointArray);
free(PointArray2D32f);
free(box);
}
cvShowImage("Result", img4);
cvWaitKey(0);
cvSaveImage("1.JPG", img4);
cvReleaseImage(&img2);
cvReleaseImage(&img3);
cvDestroyWindow("Source");
cvDestroyWindow("Result");
return 0;
}




没有更多推荐了,返回首页