#include<opencv.hpp>
#include<math.h>
#include<iostream>
using namespace std;
using namespace cv;
int main()
{
Mat image,image_gray,thresh_image;
image = imread("D:/2015project/picture/circle.jpeg");
if (!image.data)
{
cout << "Wrong";
return -1;
}
cvtColor(image, image_gray, CV_BGR2GRAY);
//阈值分割方法1:手动调节阈值
//threshold(image_gray, thresh_image,210, 255, CV_THRESH_BINARY);
//阈值分割方法2:使用大津阈值自动分割
threshold(image_gray, thresh_image, 0, 255, CV_THRESH_OTSU);
imshow("image_gray", image_gray);
imshow("thresh_image", thresh_image);
vector<vector<Point>> contours;
vector<Vec4i>hierachy;
findContours(thresh_image, contours, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point());
vector<Moments>mom(contours.size());
vector<Point2f> ccs(contours.size());
for (int i = 0; i < contours.size(); i++)
{
mom[i] = moments(contours[i]);
//计算矩的中心
ccs[i] = Point(static_cast<float>(mom[i].m10 / mom[i].m00), static_cast<float>(mom[i].m01 / mom[i].m00));
}
for (int i =0; i < contours.size(); i++)
{
drawContours(image, contours, i, Scalar(0, 0, 255), 1, 8, hierachy);
circle(image, ccs[i], 3, Scalar(255, 0, 0));
}
imshow("imagelast", image);
waitKey(0);
}
霍夫圆检测
经霍夫变换后检测圆的输出矢量,每个矢量包含三个元素的浮点矢量(x,y,radius)
假设圆上点(x,y)已知,半径radius固定,θ在0-360间变换,计算圆心坐标。
根据θ的变换范围,可以计算出虚线代表的圆,虚线代表的圆相交于一点,这一点即为我们所求的圆心。
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include<opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
//【1】载入原始图和Mat变量定义
Mat srcImage = imread("D:/2015project/picture/circle.jpeg"); //工程目录下应该有一张名为1.jpg的素材图
Mat midImage, dstImage;//临时变量和目标图的定义
//D:/2015project/picture/circle.jpeg
//D:/2015project/2018.1.4/picture/a.png
//【2】显示原始图
//imshow("【原始图】", srcImage);
//【3】转为灰度图,进行图像平滑
cvtColor(srcImage, midImage, CV_BGR2GRAY);//转化边缘检测后的图为灰度图
GaussianBlur(midImage, midImage, Size(9, 9), 2, 2);
//threshold(midImage, midImage, 0, 255, CV_THRESH_OTSU);
imshow("midImage", midImage);
//【4】进行霍夫圆变换
vector<Vec3f> circles;
HoughCircles(midImage, circles, CV_HOUGH_GRADIENT, 1.5, 10, 80, 75, 0, 0);//得到包含三个元素的矢量
//【5】依次在图中绘制出圆
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]);
cout << i << endl;
cout << "x=" << cvRound(circles[i][0]) << " y=" << cvRound(circles[i][1]) << endl;
cout << endl;
//绘制圆心
circle(srcImage, center, 10, Scalar(0, 0, 0), -1, 8, 0);//thickness为负数,表示填充
//imshow("【效果图原心】"+i, srcImage);
//绘制圆轮廓
circle(srcImage, center, radius, Scalar(155, 50, 255), 3, 8, 0);//thickness为正,表示轮廓线的粗细
//imshow("【效果图】"+i, srcImage);
}
//【6】显示效果图
imshow("效果图", srcImage);
imwrite("D:/2015project/2018.1.4/picture/dst_circle.png", srcImage);
waitKey(0);
return 0;
}