59 二值图像分析—霍夫直线检测
代码
import cv2 as cv
import numpy as np
def canny_demo(image):
t = 80
canny_output = cv.Canny(image, t, t * 2)
return canny_output
src = cv.imread("../images/sudoku.png")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)
binary = canny_demo(src)
cv.imshow("binary", binary)
lines = cv.HoughLines(binary, 1, np.pi / 180, 150, None, 0, 0)
if lines is not None:
for i in range(0, len(lines)):
rho = lines[i][0][0]
theta = lines[i][0][1]
a = np.cos(theta)
b = np.sin(theta)
x0 = a * rho
y0 = b * rho
pt1 = (int(x0 + 1000 * (-b)), int(y0 + 1000 * (a)))
pt2 = (int(x0 - 1000 * (-b)), int(y0 - 1000 * (a)))
cv.line(src, pt1, pt2, (0, 0, 255), 3, cv.LINE_AA)
# 显示
cv.imshow("hough line demo", src)
cv.waitKey(0)
cv.destroyAllWindows()
实验结果
解释
图像霍夫变换是一种特别有用的图像变换,通过把图像的坐标从2D平面坐标系变换到极坐标空间,可以发现原来在平面坐标难以提取的几何特征信息(如:直线、圆等),图像的直线与圆检测就是典型的利用霍夫空间特性实现二值图像几何分析的例子。假设有如下的直线参数方程:
r = x*cos(theta) + y * sin(theta)
其中角度theta指r与X轴之间的夹角,r为到直线几何垂直距离。
OpenCV关于霍夫直线检测有两个API,我们首先分享第一个函数,它是提取到直线在霍夫空间得几何特征,然后输出直线得两个极坐标参数。根据这两个参数我们可以组合得到空间坐标直线。该API如下:
lines = cv.HoughLines(image, rho, theta, threshold[, lines[, srn[, stn[, min_theta[, max_theta]]]]])
Image
输入图像Lines
输出直线Rho
极坐标r得步长Theta
角度步长Threshold
累加器阈值Srn
、stn
多尺度霍夫变换时候需要得参数,经典霍夫变换不需要min_theta
最小角度max_theta
最大角度
所有内容均来源于贾志刚老师的知识星球——OpenCV研习社,本文为个人整理学习,已获得贾老师授权,有兴趣、有能力的可以加入贾老师的知识星球进行深入学习。