/*****************************************************
测试程序 HoughLines_Demo 霍夫直线变换——直线检测
时间:2016年8月28日
//【标准霍夫变换】
//参数:输入,输出, rho ,theta ,最小阈值,最大阈值
HoughLines( edges, s_lines, 1, CV_PI/180, min_threshold, 0, 0 );
******************************************************/
Mat src, edges; //原图像,边缘
Mat src_gray; //灰度
Mat standard_hough, probabilistic_hough; //输出
int min_threshold = 50;
int max_trackbar = 150;
const char* standard_name = "Standard Hough Lines Demo";
const char* probabilistic_name = "Probabilistic Hough Lines Demo";
int s_trackbar = max_trackbar;
int p_trackbar = max_trackbar;
//【函数头】
void help();
void Standard_Hough( int, void* );
void Probabilistic_Hough( int, void* );
int main(void)
{
/// Read the image
src = imread( "building.jpg", 1 );
//【1、灰度化,Canny => 提取边缘】
cvtColor( src, src_gray, COLOR_RGB2GRAY );
Canny( src_gray, edges, 50, 200, 3 );
//【创建滚动条,调节阈值(最小)】
char thresh_label[50];
sprintf( thresh_label, "Thres: %d + input", min_threshold );
namedWindow( standard_name, WINDOW_AUTOSIZE );
createTrackbar( thresh_label, standard_name, &s_trackbar, max_trackbar, Standard_Hough); //标准霍夫直线
namedWindow( probabilistic_name, WINDOW_AUTOSIZE );
createTrackbar( thresh_label, probabilistic_name, &p_trackbar, max_trackbar, Probabilistic_Hough); //概率霍夫直线
//【初始化】
Standard_Hough(0, 0);
Probabilistic_Hough(0, 0);
waitKey(0);
return 0;
}
void help()
{
printf("\t Hough Transform to detect lines \n ");
printf("\t---------------------------------\n ");
printf(" Usage: ./HoughLines_Demo <image_name> \n");
}
//【标准霍夫变换】
void Standard_Hough( int, void* )
{
// 【1、定义输出向量】
vector<Vec2f> s_lines;
// 【2、转换边缘】
cvtColor( edges, standard_hough, CV_GRAY2BGR ); //彩色化
//【3、标准霍夫变换】
//参数:输入,输出, rho ,theta ,最小阈值,最大阈值
HoughLines( edges, s_lines, 1, CV_PI/180, min_threshold + s_trackbar, 0, 0 );
//【4、根据输出,转换参数(r,theta)向量,绘制在边缘上图像】
for( size_t i = 0; i < s_lines.size(); i++ ) //存储line数组
{ //根据角度,半径,构造两点
float r = s_lines[i][0], t = s_lines[i][1];
double cos_t = cos(t), sin_t = sin(t);
double x0 = r*cos_t, y0 = r*sin_t;
double alpha = 1000;
Point pt1( cvRound(x0 + alpha*(-sin_t)), cvRound(y0 + alpha*cos_t) );
Point pt2( cvRound(x0 - alpha*(-sin_t)), cvRound(y0 - alpha*cos_t) );
line( standard_hough, pt1, pt2, Scalar(255,0,0), 3, CV_AA);
}
imshow( standard_name, standard_hough );
}
//【概率霍夫变换】
void Probabilistic_Hough( int, void* )
{
//【步骤:同理】
//【1、定义输出向量】
//【2、转换边缘】
//【3、标准霍夫变换】
//【4、根据输出,转换(两点)向量,绘制在边缘上图像】
vector<Vec4i> p_lines;
cvtColor( edges, probabilistic_hough, CV_GRAY2BGR );
HoughLinesP( edges, p_lines, 1, CV_PI/180, min_threshold + p_trackbar, 30, 10 );
for( size_t i = 0; i < p_lines.size(); i++ )
{
Vec4i l = p_lines[i];
line( probabilistic_hough, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(255,0,0), 3, CV_AA);
}
imshow( probabilistic_name, probabilistic_hough );
}
如同通过调节阈值,检测不同数量的直线。
左图是标准霍夫变换,右图是概率霍夫变换。