/*****************************************************
测试程序 【HoughCircle_Demo 霍夫圆变换——边缘检测】
时间:2016年8月30日
参数:src,输出数组,霍夫梯度,dp,最小圆心距,Canny阈值,累加阈值
HoughCircles( src_gray, circles, CV_HOUGH_GRADIENT, 1, src_gray.rows/8, cannyThreshold, accumulatorThreshold, 0, 0 );
******************************************************/
namespace
{
// windows and trackbars name
const std::string windowName = "Hough Circle Detection Demo";
const std::string cannyThresholdTrackbarName = "Canny threshold";
const std::string accumulatorThresholdTrackbarName = "Accumulator Threshold";
const std::string usage = "Usage : tutorial_HoughCircle_Demo <path_to_input_image>\n";
// initial and max values of the parameters of interests.
const int cannyThresholdInitialValue = 200;
const int accumulatorThresholdInitialValue = 50;
const int maxAccumulatorThreshold = 200;
const int maxCannyThreshold = 255;
void HoughDetection(const Mat& src_gray, const Mat& src_display, int cannyThreshold, int accumulatorThreshold)
{
//【检测结果 向量】
std::vector<Vec3f> circles;
// 【霍夫圆检测】
//参数:src,输出数组,霍夫梯度,dp?,最小圆心距,Canny阈值,累加阈值
HoughCircles( src_gray, circles, CV_HOUGH_GRADIENT, 1, src_gray.rows/8, cannyThreshold, accumulatorThreshold, 0, 0 );
//【复制显示】
Mat display = src_display.clone();
for( size_t i = 0; i < circles.size(); i++ )
{
Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); //Center ——(x,y)
int radius = cvRound(circles[i][2]); //半径——r
circle( display, center, 3, Scalar(0,255,0), -1, 8, 0 ); //【中心圆】
circle( display, center, radius, Scalar(0,0,255), 3, 8, 0 ); //【外轮廓圆】
}
// shows the results
imshow( windowName, display);
}
}
int main(void)
{
Mat src, src_gray;
//【1、读入并检测】
src = imread("stuff.jpg", 1 );
//【2、转为灰度,并模糊除噪——预处理】
cvtColor( src, src_gray, COLOR_BGR2GRAY );
GaussianBlur( src_gray, src_gray, Size(9, 9), 2, 2 );
//【声明&初始化两个参数】declare and initialize both parameters that are subjects to change
int cannyThreshold = cannyThresholdInitialValue;
int accumulatorThreshold = accumulatorThresholdInitialValue;
//【窗口 + 滚动条】create the main window, and attach the trackbars
namedWindow( windowName, WINDOW_AUTOSIZE );
createTrackbar(cannyThresholdTrackbarName, windowName, &cannyThreshold,maxCannyThreshold);
createTrackbar(accumulatorThresholdTrackbarName, windowName, &accumulatorThreshold, maxAccumulatorThreshold);
// 【无限循环显示更新输出知道press Q 】
int key = 0;
while(key != 'q' && key != 'Q')
{
//【参数不能 == 0】
cannyThreshold = std::max(cannyThreshold, 1);
accumulatorThreshold = std::max(accumulatorThreshold, 1);
//【回调函数,检测】
//参数:src【gray】, src【显示】,canny阈值,累加阈值
HoughDetection(src_gray, src, cannyThreshold, accumulatorThreshold);
key = waitKey(10);
}
return 0;
}
【opencv练习24 - 霍夫圆变换——圆检测】
最新推荐文章于 2024-08-12 08:58:49 发布