霍夫圆变换的工作方式与前一个教程中解释的霍夫线变换大致类似。
在线检测情况下,线由两个参数定义。在圆圈情况下,我们需要三个参数来定义圆:
在哪里定义中心位置(格力点)并且是半径,这允许我们完全定义一个圆,如下所示:
为了提高效率,OpenCV实现了一种比标准Hough变换稍微复杂的检测方法:霍夫梯度法。有关详细信息,请查看学习OpenCV或您最喜欢的计算机视觉参考书目
代码
- 这个程序做什么用的?
- 加载图像并模糊图像以减少噪点
- 将霍夫圆变换应用于模糊图像。
- 在窗口中显示检测到的圆圈。
- 我们将解释的示例代码可以从这里下载。可以在此处找到稍微更漂亮的版本(显示Hough标准和带轨迹栏的概率以更改阈值)。
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
using namespace cv;
/** @function main */
int main(int argc, char** argv)
{
Mat src, src_gray;
/// Read the image
src = imread( argv[1], 1 );
if( !src.data )
{ return -1; }
/// Convert it to gray
cvtColor( src, src_gray, CV_BGR2GRAY );
/// Reduce the noise so we avoid false circle detection
GaussianBlur( src_gray, src_gray, Size(9, 9), 2, 2 );
vector<Vec3f> circles;
/// Apply the Hough Transform to find the circles
HoughCircles( src_gray, circles, CV_HOUGH_GRADIENT, 1, src_gray.rows/8, 200, 100, 0, 0 );
/// Draw the circles detected
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 center
circle( src, center, 3, Scalar(0,255,0), -1, 8, 0 );
// circle outline
circle( src, center, radius, Scalar(0,0,255), 3, 8, 0 );
}
/// Show your results
namedWindow( "Hough Circle Transform Demo", CV_WINDOW_AUTOSIZE );
imshow( "Hough Circle Transform Demo", src );
waitKey(0);
return 0;
}
说明
-
加载图像
src = imread( argv[1], 1 ); if( !src.data ) { return -1; }
-
将其转换为灰度:
cvtColor ( src , src_gray , CV_BGR2GRAY );
-
应用高斯模糊以减少噪音并避免假圆检测:
高斯模糊( src_gray , src_gray , 尺寸(9 , 9 ), 2 , 2 );
-
继续应用霍夫圆变换:
vector<Vec3f> circles; HoughCircles( src_gray, circles, CV_HOUGH_GRADIENT, 1, src_gray.rows/8, 200, 100, 0, 0 );
与参数:
- src_gray:输入图像(灰度)
- 圆圈:存储3个值的集合的向量:对于每个检测到的圆圈。
- CV_HOUGH_GRADIENT:定义检测方法。目前这是OpenCV中唯一可用的
- dp = 1:分辨率的反比
- min_dist = src_gray.rows / 8:检测到的中心之间的最小距离
- param_1 = 200:内部Canny边缘检测器的上限阈值
- param_2 = 100 *:中心检测的阈值。
- min_radius = 0:要检测的最小无线电。如果未知,则默认为零。
- max_radius = 0:要检测的最大半径。如果未知,则默认为零
-
绘制检测到的圆圈:
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 center circle( src, center, 3, Scalar(0,255,0), -1, 8, 0 ); // circle outline circle( src, center, radius, Scalar(0,0,255), 3, 8, 0 ); }
你可以看到我们将用红色绘制圆圈,用小绿点绘制中心
-
显示检测到的圆圈:
namedWindow ( “Hough Circle Transform Demo” , CV_WINDOW_AUTOSIZE ); imshow ( “Hough Circle Transform Demo” , src );
-
等待用户退出程序
waitKey (0 );
结果
使用测试图像运行上面代码的结果如下所示: