本文是对OpenCV2.4.13文档的部分翻译,作个人学习之用,并不完整。
Hough圆形变换:
在直线检测中,线条由(r , θ)来定义,圆形中,我们需要三个参数来定义一个圆:
x,y定义了圆心的位置,r定义了半径。
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
using namespace cv;
namespace
{
// 窗口和滑动条名字
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";
// 初始值和最大值
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;
// 执行实际检测(输入图像(灰度图),包含三个值的向量(x,y,r),分辨率的反比,检测圆的最小距离,中心检测的阈值,检测的最小半径,检测的最大半径)
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]));
int radius = cvRound(circles[i][2]);
// 圆心
circle( display, center, 3, Scalar(0,255,0), -1, 8, 0 );
// 圆边缘
circle( display, center, radius, Scalar(0,0,255), 3, 8, 0 );
}
// 显示结果
imshow( windowName, display);
}
}
int main()
{
Mat src, src_gray;
// Read the image
src = imread("HappyFish.jpg", 1);
if( !src.data )
{
std::cerr<<"Invalid input image\n";
std::cout<<usage;
return -1;
}
// 转换为灰度图
cvtColor( src, src_gray, COLOR_BGR2GRAY );
// 消噪,避免错误的圆形检测
GaussianBlur( src_gray, src_gray, Size(9, 9), 2, 2 );
//要改变的参数的声明和初始化
int cannyThreshold = cannyThresholdInitialValue;
int accumulatorThreshold = accumulatorThresholdInitialValue;
// 创建主窗口,添加滑动条
namedWindow( windowName, WINDOW_AUTOSIZE );
createTrackbar(cannyThresholdTrackbarName, windowName, &cannyThreshold,maxCannyThreshold);
createTrackbar(accumulatorThresholdTrackbarName, windowName, &accumulatorThreshold, maxAccumulatorThreshold);
// 用有限循环来显示
// 更新输出图像的内容
// 直到用户按下q或Q
int key = 0;
while(key != 'q' && key != 'Q')
{
// 这些参数不能为0,需要检查
cannyThreshold = std::max(cannyThreshold, 1);
accumulatorThreshold = std::max(accumulatorThreshold, 1);
//执行检测,更新显示
HoughDetection(src_gray, src, cannyThreshold, accumulatorThreshold);
// 等待用户输入
key = waitKey(10);
}
return 0;
}
结果: