第一种:
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
using namespace cv;
using namespace std;
int sliderPos = 70;
Mat image;
void processImage(int, void*);
int main( int argc, char** argv )
{
image = imread("C:\\Users\\Administrator\\Desktop\\20140528\\129.bmp", 0);
if( image.empty() )
{
cout << "Couldn't open image " << "\n";
return 0;
}
namedWindow("result", 1);
// Create toolbars. HighGUI use.
createTrackbar( "threshold", "result", &sliderPos, 255, processImage );
processImage(0, 0);
// Wait for a key stroke; the same function arranges events processing
waitKey();
return 0;
}
// Define trackbar callback functon. This function find contours,
// draw it and approximate it by ellipses.
void processImage(int /*h*/, void*)
{
vector<vector<Point> > contours;
Mat bimage = image >= sliderPos;
findContours(bimage, contours, RETR_LIST, CHAIN_APPROX_NONE);
Mat cimage = Mat::zeros(bimage.size(), CV_8UC3);
for(size_t i = 0; i < contours.size(); i++)
{
size_t count = contours[i].size();
if( count < 6 )
continue;
Mat pointsf;
Mat(contours[i]).convertTo(pointsf, CV_32F);
RotatedRect box = fitEllipse(pointsf);
if( MAX(box.size.width, box.size.height) > MIN(box.size.width, box.size.height)*30 )
continue;
drawContours(cimage, contours, (int)i, Scalar::all(255), 1, 8);
ellipse(cimage, box, Scalar(0,0,255), 1, LINE_AA);
ellipse(cimage, box.center, box.size*0.5f, box.angle, 0, 360, Scalar(0,255,255), 1, LINE_AA);
Point2f vtx[4];
box.points(vtx);
for( int j = 0; j < 4; j++ )
line(cimage, vtx[j], vtx[(j+1)%4], Scalar(0,255,0), 1, LINE_AA);
}
imshow("result", cimage);
}
第二种:
Mat qxAlgorithm::checkEllipse(Mat src)
{
Mat gray;
if( !src.data )
return gray;
cvtColor( src, gray, CV_BGR2GRAY );
//高斯模糊平滑
GaussianBlur( gray, gray, Size(3, 3), 2, 2 );
vector<Vec3f> circles;
circles.clear ();
//霍夫变换
HoughCircles( gray, circles, CV_HOUGH_GRADIENT, 1, 50, 50, 50, 0,100 );
//在原图中画出圆心和圆
for( size_t i = 0; i < circles.size(); i++ )
{
//提取出圆心坐标
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
//提取出圆半径
int radius = cvRound(circles[i][2]);
//圆心
circle( src, center, 3, Scalar(0,255,0), -1, 8, 0 );
//圆
circle( src, center, radius, Scalar(0,0,255), 3, 8, 0 );
}
return src;
}