cv2.HoughLines()
,cv2.HoughLinesP()
可以参考链接:霍夫变换检测直线的原理深入理解
import cv2
import numpy as np
img = cv2.imread('dave.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 30, 100, apertureSize=3)
lines = cv2.HoughLines(edges, 1, np.pi / 180, 100)
print(lines[0])
print(lines[1])
print(lines.shape)
print(lines)
for i in range(15):
for rho, theta in lines[i]:
print(rho, theta)
a = np.cos(theta)
b = np.sin(theta)
x0 = a * rho
y0 = b * rho
x1 = int(x0 + 1000 * (-b))
y1 = int(y0 + 1000 * a)
x2 = int(x0 - 1000 * (-b))
y2 = int(y0 - 1000 * a)
cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
# cv2.imshow('img', img)
# cv2.waitKey(0)
cv2.imwrite('houghlines3.jpg', img)
运行结果如下:
在霍夫变换中,决定一条直线需要2个参数,需要大量的计算。为了降低计算量,提出霍夫变换的优化版本,概率霍夫变换。它不需要考虑所有的点,需要部分点就可以估计直线。那么,我们也需要降低阈值。下面的流程图给出了两种算法的区别:
在OpenCV中,使用的是Progreesive Probabilistic Hough Transform. 函数为cv2.HoughLineP()
. 它有两个参数:
minLineLength
:线的最小长度,小于该值被去除。maxLineGap
:两条直线的距离,小于该值则认为是一条直线。该函数返回直线的两个端点。在上面的论述中,返回的是直线的参数,那么不得不找到所有的点。例子如下:
import cv2
import numpy as np
img = cv2.imread('dave.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
minLineLength = 100
maxLineGap = 10
lines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength,maxLineGap)
for x1,y1,x2,y2 in lines[0]:
cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)
cv2.imwrite('houghlines5.jpg',img)
运行结果如下: