原理:
霍夫变换圆检测原理和直线相似,直线检测需要两个参数(theta,r)。圆形需要圆心做坐标两个参数和半径。
对左边做霍夫圆变换可以发现圆形的位置变成了一个两点,说明
HoughCircles(
image,
outputArray circles, 发现圆信息
int method, 方法-HOUGH_GRADIENT
double dp, dp = 1;
double mindist, 最短距离,可以分辨是两个圆的圆心的最小像素距离,否则认为是同心圆
double param1, canny edge detection low threshold,默认是100?
double param2, 中心点累加器阈值–候选圆心
int minradius, 最小半径
int maxradius 最大半径
)
代码
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
using namespace cv;
using namespace std;
/** @function main */
int main(int argc, char** argv)
{
Mat src, src_gray;
///读到一张图片
src = imread("1.jpg");
if( !src.data )
{ return -1; }
/// 转换到灰度
cvtColor( src, src_gray, CV_BGR2GRAY );
/// 降低噪声以避免我们得到错误的检测
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, 10, 100, 10, 150, 220 );
// src_gray: Input image (grayscale)
//circles: A vector that stores sets of 3 values: x_{c}, y_{c}, r for each detected circle.
//CV_HOUGH_GRADIENT: Define the detection method. Currently this is the only one available in OpenCV
//dp = 1: The inverse ratio of resolution
//min_dist = src_gray.rows/8: Minimum distance between detected centers
//param_1 = 200: Upper threshold for the internal Canny edge detector
//param_2 = 100*: Threshold for center detection.
//min_radius = 0: Minimum radio to be detected. If unknown, put zero as default.
//max_radius = 0: Maximum radius to be detected. If unknown, put zero as default
/// 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 );
}
cout<<src.rows;
/// Show your results
namedWindow( "Hough Circle Transform Demo", CV_WINDOW_AUTOSIZE );
imshow( "Hough Circle Transform Demo", src );
waitKey(0);
return 0;
}
效果: