霍夫变换(Hough Circle Transform)-圆检测

官网教程

参数不太好选,API比较难用


代码

#include 
#include 

using namespace cv;
using namespace std;

//测试使用
//int Max_Threshold = 300;
//const int Max_Value = 600;

//int Low_Threshold = 100;
//const int Low_Value = 300;

cv::Mat src_gray,src,Terminal;
//测试使用
//void MyCanny(int,void*)
//{
//	Mat tmp;
//	cv::medianBlur(src_gray,tmp,5);
//	Canny(tmp,tmp,Low_Threshold,Max_Threshold,3);
//	imshow("Canny", tmp);
//	Terminal = tmp.clone();	
//}


int main(void)
{

    src = imread("../res/coins.png");
	if(src.empty())
	{
		cout << "can't load image" << endl;
	}		
	cvtColor(src,src_gray, cv::COLOR_BGR2GRAY);

    //测试使用
	// createTrackbar("Canny High Threshold","Canny",&Max_Threshold,Max_Value,MyCanny);
	// createTrackbar("Canny Low Threshold","Canny",&Low_Threshold,Low_Value,MyCanny);

	cv::medianBlur(src_gray,src_gray,5);
	Canny(src_gray,src_gray,180,600,3); //参数是自己通过createTrackbar调出来的
	imshow("after Canny" , src_gray);

	vector<Vec3f> circles;
	HoughCircles(src_gray,circles, HOUGH_GRADIENT,1,100,200,20,50,200); //测试出来的参数,

	for(int i=0; i<circles.size(); i++)
	{
		Vec3i c = circles[i];
		Point center = Point(c[0],c[1]);

		circle(src,center,1,Scalar(0,0,0),3,LINE_AA);
		int radius = c[2];
		circle(src,center,radius,Scalar(0,0,0),3,LINE_AA);
	}

	imshow("Hough Circles",src);
		
	waitKey(0);
		
	return 0;
};


结果:

先Canny进行边缘检测:

霍夫变换(Hough Circle Transform)-圆检测_第1张图片

检测结果:

霍夫变换(Hough Circle Transform)-圆检测_第2张图片

OpenCV API

void cv::HoughCircles
(
InputArray image,     // 8-bit, single-channel, grayscale input image.
OutputArray circles,    // 输出检测到的圆,参数是 float型 (x,y,radius)
int method,        // 检测方法: HOUGH_GRADIENT
double dp,        // accumulator resolution=(1/dp) × \times ×image resolution
double minDist,      //检测到两个圆之间的最小距离
double param1 = 100,    // 内部调用了Canny edge ,这个是高阈值,低阈值是此参数的1/2
double param2 = 100,    // 是霍夫空间检测圆心的收集器的阈值,
int minRadius = 0,    // Minimum circle radius.
int maxRadius = 0     //Maximum circle radius ,If < 0, 只检测圆心
)

你可能感兴趣的:(opencv)