代码如下:
#include
#include
using namespace std;
using namespace cv;
vector HoughCirlesSearch(Mat image);
int main() {
Mat A1 = imread("C://Users//颜俊毅//Desktop//答题卡填涂.jpg");
Mat A2(800, 800, A1.depth(),A1.channels());
resize(A1, A2,A2.size(),0,0);
imshow("归一化", A2);
cout<<HoughCirlesSearch(A2);
waitKey(0);
return 0;
}
vector HoughCirlesSearch(Mat image)
{
//找出图片的中心
Mat grayImage, dstImage, thresholdImage, GaussianImage;
int centerhingh = image.cols / 2;
int centerwidth = image.rows / 2;
cvtColor(image, grayImage, CV_BGR2GRAY); //灰度化
threshold(grayImage, thresholdImage, 40, 255, THRESH_BINARY); //二值化
GaussianBlur(grayImage, GaussianImage, Size(9, 9), 2, 2); //高斯模糊使图像变平滑
//imshow("预处理", grayImage);
image.copyTo(dstImage);
//创建圆的集合
vector<Vec3f>circles;
//霍夫圆检测
HoughCircles(GaussianImage, circles, CV_HOUGH_GRADIENT, 1, 100, 100, 20, 10, 50);
vector<Point2f> top, bot, result;
for (size_t i = 0; i < circles.size(); i++)
{
Point2f centerCircles(round(circles[i][0]), round(circles[i][1]));
int radius = (int)round(circles[i][2]);
circle(dstImage, centerCircles, 3, Scalar(0, 255, 0), -1, 4, 0);
circle(dstImage, centerCircles, radius, Scalar(0, 0, 255), 3, 4, 0);
if (centerCircles.y < centerhingh)
{
top.push_back(centerCircles);
}
else
{
bot.push_back(centerCircles);
}
//cout << centerCircles << endl << endl;
}
cout << top[0] << endl << endl;
cout << top[1] << endl << endl;
cout << bot[0] << endl << endl;
cout << bot[1] << endl << endl;
cout << "-------------" << endl << endl;
Point2f topleft = top[0].x > top[1].x ? top[1] : top[0];
Point2f topright = top[0].x > top[1].x ? top[0] : top[1];
Point2f botleft = bot[0].x > bot[1].x ? bot[1] : bot[0];
Point2f botright = bot[0].x > bot[1].x ? bot[0] : bot[1];
result.push_back(topleft);
result.push_back(topright);
result.push_back(botleft);
result.push_back(botright);
cout << topleft << endl << endl;
cout << topright << endl << endl;
cout << botleft << endl << endl;
cout << botright << endl << endl;
cout << "-------------" << endl << endl;
//imshow("检测后", dstImage);
return result;
}