1.标准霍夫变换 HoughLines()函数
C++:void HoughLines(InputArray image, OutputArray lines, double rho, double theta, int threshold, double srn=0, double stn=0, double min_theta=0, double max_theta=CV_PI )
InputArray image:输入InputArray 类型的 image,即源图像,通常为8位的单通道二进制图像;
OutputArray lines:输出OutputArray 类型的 lines,即经过调用HoughLines函数后用lines来存储霍夫变换检测到的线条矢量;
double rho:输入double 类型的 rho,即极径,如图中所示的 r;
double theta:输入double 类型的 theta,即极角,如图中所示的 theta;
int threshold:输入int 类型的 threshold,即阈值(识别某部分为图中的一条直线),只有大于阈值 threshold 的线段才能被检测通过并返回到结果中;
double srn=0 和 double stn=0:默认值为0,当选择为默认值时,表示使用经典的霍夫变换。
2.累计概率霍夫变换 HoughLinesP()函数
C++:void HoughLinesP(InputArray image, OutputArray lines, double rho, double theta, int threshold, doubleminLineLength=0, double maxLineGap=0 )
InputArray image:输入InputArray 类型的 image,即源图像,通常为8位的单通道二进制图像;
OutputArray lines:输出OutputArray 类型的 lines,即经过调用HoughLines函数后用lines来存储霍夫变换检测到的线条矢量,输出的两点是线段的两个端点((x_1、y_1)、(x_2、y_2)),两个端点为检测到线段的结束点;
double rho:输入double 类型的 rho,即极径,如图中所示的 r;
double theta:输入double 类型的 theta,即极角,如图中所示的 theta;
int threshold:输入int 类型的 threshold,即阈值(识别某部分为图中的一条直线),只有大于阈值 threshold 的线段才能被检测通过并返回到结果中;
doubleminLineLength:输入double 类型的 minLineLength,默认值为0,表示最低线段的长度,小于该值的线段将被忽略;
double maxLineGap:输入double 类型的 maxLineGap,默认值为0,表示允许同一行点与点之间连接起来的最大距离。
参考代码:
if 0
vector lines;
HoughLines(dst, lines, 1, CV_PI/180, 100, 0, 0 );
for( size_t i = 0; i < lines.size(); i++ )
{
float rho = lines[i][0], theta = lines[i][1]; //极径和极角
Point pt1, pt2; //霍夫变换得到的两点,x0=(pt1.x、pt1.y),y0=(pt2.x、pt2.y)
double a = cos(theta), b = sin(theta); //确定cos和sin值
double x0 = a*rho, y0 = b*rho; //确定x0与y0的值
pt1.x = cvRound(x0 + 1000*(-b));
pt1.y = cvRound(y0 + 1000*(a));
pt2.x = cvRound(x0 - 1000*(-b));
pt2.y = cvRound(y0 - 1000*(a));
line( cdst, pt1, pt2, Scalar(0,0,255), 3, CV_AA);
}
#else
vector lines;
HoughLinesP(dst, lines, 1, CV_PI/180, 50, 50, 10 );
for( size_t i = 0; i < lines.size(); i++ )
{
Vec4i l = lines[i];
line( cdst, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,0,255), 3, CV_AA);
}
#endif
imshow(“source”, src);
imshow(“detected lines”, cdst);
waitKey();
return 0;
}
其中:通过x0和y0向上向下个找两点,确定一条直线。1000也可以用其他的数代替;
int cvRound (double value) //把浮点数转化成整数