OpenCV4入门教程132:LSD快速直线检测

索引地址:系列索引

使用LSD算法检测图片中所有可能的直线并绘制出来

测试代码1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include "opencv2/opencv.hpp"

using namespace std;
using namespace cv;

int main()
{
Mat image = imread("Test.png");
Mat imgGray;
cvtColor(image, imgGray, COLOR_BGR2GRAY);

Ptr<LineSegmentDetector> detector = createLineSegmentDetector();

vector<Vec4f> lines;
detector->detect(imgGray,
lines);

Mat result(image.size(),
CV_8UC3,
Scalar(0, 0, 0));

// detector->drawSegments(result,
// lines);

// or the following

Scalar color(0,0,255);
int thickness = 2;
for(int i=0; i<lines.size(); i++)
{
line(result,
Point(lines.at(i)[0],
lines.at(i)[1]),
Point(lines.at(i)[2],
lines.at(i)[3]),
color,
thickness);
}

imshow("image", image);
imshow("result", result);

waitKey();

return 0;
}

效果为

lines

测试代码2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 功能:代码 5-17 LSD 快速线检测
// 作者:朱伟 zhu1988wei@163.com
// 来源:《OpenCV图像处理编程实例》
// 博客:http://blog.csdn.net/zhuwei1988
// 更新:2016-8-1
// 说明:版权所有,引用或摘录请联系作者,并按照上面格式注明出处,谢谢。//
#include <iostream>
#include <string>
#include "opencv2/core/core.hpp"
#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace std;
using namespace cv;
int main()
{

cv::Mat srcImage =
cv::imread("..\\images\\building.jpg", 0);
if (!srcImage.data)
return -1;
// canny边缘检测
Canny(srcImage, srcImage, 50, 200, 3);
// 创建LSD检测类
#if 1
Ptr<LineSegmentDetector> ls = createLineSegmentDetector(LSD_REFINE_STD);
#else
Ptr<LineSegmentDetector> ls = createLineSegmentDetector(LSD_REFINE_NONE);
#endif
double start = double(getTickCount());
vector<Vec4f> lines_std;
// 线检测
ls->detect(srcImage, lines_std);
double duration_ms = (double(getTickCount()) - start) * 1000 / getTickFrequency();
std::cout << "It took " << duration_ms << " ms." << std::endl;
// 绘图线检测结果
Mat drawnLines(srcImage);
ls->drawSegments(drawnLines, lines_std);
cv::imshow("Standard refinement", drawnLines);
cv::waitKey();
return 0;
}

输出为

1
It took 16.2452 ms.

效果为

lsd


OpenCV4入门教程132:LSD快速直线检测
https://feater.top/opencv/opencv-lsd-lines-detection/
作者
JackeyLea
发布于
2020年11月10日
许可协议