opencv-060-二值图像分析(霍夫直线检测二)

知识点

OpenCV中还有另外一个霍夫直线检测的API,该API更为常用,它会直接返回直线的空间坐标点,比返回霍夫空间参数更加的直观,容易理解,而且还可以声明线段长度、间隔等参数,非常有用。

API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void cv::HoughLinesP(
InputArray image,
OutputArray lines,
double rho,
double theta,
int threshold,
double minLineLength = 0,
double maxLineGap = 0
)
Image输入二值图像
Lines 返回的直线两个点
Rho 极坐标r得步长
Theta角度步长
Threshold累加器阈值
minLineLength最小线段长度
maxLineGap线段间隔

代码(c++,python)

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
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

/*
* 二值图像分析(霍夫直线检测二)
*/
int main() {
Mat src = imread("../images/line.png");
if (src.empty()) {
cout << "could not load image.." << endl;
}
imshow("input", src);

// 去噪声与二值化
Mat binary;
Canny(src, binary, 80, 160);

// 霍夫直线检测
vector<Vec4i> lines;
HoughLinesP(binary, lines, 1, CV_PI / 180, 80, 30, 10);

// 绘制直线
Mat result = Mat::zeros(src.size(), src.type());
for (size_t i = 0; i < lines.size(); ++i) {
line(result, Point(lines[i][0], lines[i][1]),
Point(lines[i][2], lines[i][3]), Scalar(0, 0, 255));
}

imshow("contours", result);

waitKey(0);
return 0;
}
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
import cv2 as cv
import numpy as np

def canny_demo(image):
t = 80
canny_output = cv.Canny(image, t, t * 2)
cv.imwrite("D:/canny_output.png", canny_output)
return canny_output


src = cv.imread("D:/images/morph01.png")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)
binary = canny_demo(src)
cv.imshow("binary", binary)

linesP = cv.HoughLinesP(binary, 1, np.pi / 180, 50, None, 50, 10)
if linesP is not None:
for i in range(0, len(linesP)):
l = linesP[i][0]
cv.line(src, (l[0], l[1]), (l[2], l[3]), (255, 0, 0), 1, cv.LINE_AA)

cv.imshow("hough line demo", src)
cv.imwrite("D:/contours_analysis.png", src)
cv.waitKey(0)
cv.destroyAllWindows()

结果

代码地址

github