您的位置:首页 > 运维架构

OpenCV入门:Hough霍夫变换-直线选择(HoughLinesP)

2018-01-16 09:32 751 查看
霍夫变换HoughLinesP函数

#include <iostream>
#include <fstream>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <math.h>
using namespace cv;
using namespace std;
void drawDetectLines(Mat& image, const vector<Vec4i>& lines, Scalar & color)
{
// 将检测到的直线在图上画出来
vector<Vec4i>::const_iterator it = lines.begin();
while (it != lines.end())
{
Point pt1((*it)[0], (*it)[1]);
Point pt2((*it)[2], (*it)[3]);
line(image, pt1, pt2, color, 2); // 线条宽度设置为2
++it;
}
}

int main()
{
Mat image = imread("E:/CV/11.jpg");
Mat I;
cvtColor(image, I, CV_BGR2GRAY);

Mat contours;
Canny(I, contours, 125, 350);
threshold(contours, contours, 128, 255, THRESH_BINARY);
vector<Vec4i> lines;

/*
霍夫变换HoughLinesP函数的原型为:
void HoughLinesP(InputArray image,OutputArray lines, double rho, double theta, int threshold, double minLineLength=0,double maxLineGap=0 )
image为输入图像,要求是8位单通道图像
lines为输出的直线向量,每条线用4个元素表示,即直线的两个端点的4个坐标值
rho和theta分别为距离和角度的分辨率
threshold为阈值,即步骤3中的阈值
minLineLength为最小直线长度,在步骤5中要用到,即如果小于该值,则不被认为是一条直线
maxLineGap为最大直线间隙,在步骤4中要用到,即如果有两条线段是在一条直线上,但它们之间因为有间隙,所以被认为是两个线段,如果这个间隙大于该值,则被认为是两条线段,否则是一条。
*/
// 检测直线,最小投票为90,线条不短于50,间隙不小于10
HoughLinesP(contours, lines, 1, CV_PI / 180, 80, 50, 10);
drawDetectLines(image, lines, Scalar(0, 255, 0));
namedWindow("直线");
imshow("直线", image);
waitKey();
return 0;
}

效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: