运行环境 BCB 6.0~ 需要OPENCV 库支持
CvMemStorage* storage = cvCreateMemStorage(0); CvSeq* contours; CvBox2D s; char string1[22]; char string2[22]; IplImage* img = cvLoadImage( "Ellipse.jpg" ); IplImage* gray = cvCreateImage(cvGetSize(img), 8, 1 ); IplImage* gray1 = cvCreateImage(cvGetSize(img), 8, 1 ); cvCvtColor(img, gray, CV_BGR2GRAY ); cvThreshold( gray, gray1 ,30, 255, CV_THRESH_BINARY ); //图像二值化(这里按需要进行修改,椭圆应为高灰度值) cvNamedWindow( "Ellipse", 1 ); cvShowImage("Ellipse",gray1); cvSaveImage("Ellipse11.jpg",gray1); cvFindContours( gray1, storage, &contours, sizeof(CvContour), CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0)); s=cvFitEllipse2(contours); s.angle=90-s.angle;//这个地方是OPENCV的一个BUG 角度要修正一下 //cvEllipse( img, cvPointFrom32f( s.center ),cvSize(s.size.width,s.size.height), s.angle,0, 360, CV_RGB(0,0,255), 1, 8, 0 ); cvEllipseBox(img,s, CV_RGB(0,0,255),3, 8 , 0 );//画椭圆框 cvNamedWindow( "Ellipse22", 1 ); cvShowImage("Ellipse22",img);//原图上显示椭圆框 cvSaveImage("Ellipse22.jpg",img); itoa(s.size.width, string1, 10 ); itoa(s.size.height, string2, 10 ); strcat(string1,", "); strcat(string1,string2); ShowMessage( AnsiString(" 椭圆的长短轴分别为:") + string1 + AnsiString(" 像素 ")); 此程序只能检测一个椭圆,如果要检测多个椭圆,要做如下修改~ CvMemStorage* storage = cvCreateMemStorage(0); CvSeq* contours; CvBox2D s; char string1[22]; char string2[22]; char string3[22]; char string4[222]; IplImage* img = cvLoadImage( "Ellipse.jpg" ); IplImage* gray = cvCreateImage(cvGetSize(img), 8, 1 ); IplImage* gray1 = cvCreateImage(cvGetSize(img), 8, 1 ); cvCvtColor(img, gray, CV_BGR2GRAY ); cvThreshold( gray, gray1 ,100, 255, CV_THRESH_BINARY ); cvNamedWindow( "Ellipse", 1 ); cvShowImage("Ellipse",gray1); cvSaveImage("Ellipse11.jpg",gray1); int i=cvFindContours( gray1, storage, &contours, sizeof(CvContour), CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0)); itoa(i, string3, 10 ); for(CvSeq* c=contours; c!=NULL; c=c->h_next) { s=cvFitEllipse2(c); s.angle=90-s.angle; cvEllipseBox(img,s, CV_RGB(255,0,0),2, 8 , 0 );//画椭圆框 itoa(s.size.width, string1, 10 ); itoa(s.size.height, string2, 10 ); strcat(string1," "); strcat(string1,string2); strcat(string4,string1); strcat(string4," | "); } cvNamedWindow( "Ellipse22", 1 ); cvShowImage("Ellipse22",img);//原图上显示椭圆框 cvSaveImage("Ellipse22.jpg",img); ShowMessage( AnsiString(" 共找到椭圆 ") + string3 + AnsiString(" 个/n ")+ AnsiString("椭圆的长短轴分别为:") + string4 + AnsiString("像素 "));