使用霍夫线变换HoughLines()函数,进行直线检测。
API函数
void HoughLines(InputArray image,//输入图像,8位单通道的二值图像;输入图像可能被函数修改。
OutputArray lines,//直线的输出向量,每一条直线由两个元素的向量(rho,theta)表示
double rho, double theta, //直线搜索时的步进尺寸
int threshold,//最小投票数
double srn = 0, double stn = 0,//默认
double min_theta = 0, double max_theta = CV_PI);//默认
一、c++示例代码
//包含头文件
#include <opencv2/opencv.hpp>
//命名空间
using namespace cv;
using namespace std;
//全局函数声明部分
//主函数
int main()
{
//【1】载入图像
Mat image = imread("F:\\opencvtest\\testImage\\airplane.jpg");
//【2】检查是否载入成功
if (image.empty())
{
printf("读取图片错误,请确认目录下是否有imread函数指定图片存在! \n ");
return 0;
}
//【3】转换为灰度图像
Mat grayImage;
cvtColor(image, grayImage, COLOR_BGR2GRAY);
//【4】图像平滑降噪
Mat result;
blur(grayImage, result, Size(3,3));
//【5】Canny算子进行边缘检测
Mat edge;
Canny(result, edge, 30, 90, 3);
//【6】霍夫变换、直线检测
vector<Vec2f> lines;
HoughLines(edge, lines, 1, CV_PI/180, 150);
//【7】迭代器遍历向量,line()函数绘制直线
std::vector<Vec2f>::const_iterator it = lines.begin();
while (it != lines.end())
{
float rho = (*it)[0];
float theta = (*it)[1];
if (theta < CV_PI/4 || theta > 3*CV_PI/4)
{
//画垂直线
Point pt1(rho/cos(theta), 0);
Point pt2((rho - edge.rows * sin(theta)) / cos(theta), edge.rows);
line(image, pt1, pt2, Scalar(55, 100, 195), 1, LINE_AA);
}
else
{
//画水平线
Point pt1(0, rho / sin(theta));
Point pt2(edge.cols, (rho - edge.cols * cos(theta)) / sin(theta));
line(image, pt1, pt2, Scalar(55, 100, 195), 1, LINE_AA);
}
++it;
}
//【8】显示图像
imshow("17-直线检测图", image);
imshow("17-边缘检测图", edge);
//【9】保持窗口显示
waitKey(0);
return 0;
}
二、运行截图
1.Canny边缘检测图
2.Hough变换直线检测图