直线检测一般使用函数HoughLines或HoughLinesP,第二种方法为概率版本Hoygh变换,这个函数是优化版本,计算速度更快
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
x, y = frame.shape[0:2]
small_frame = cv2.resize(frame, (int(y / 2), int(x / 2)))
gray = cv2.cvtColor(small_frame, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 120)
minLineLength = 10
maxLineGap = 5
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 100, minLineLength, maxLineGap)
try:
for x1, y1, x2, y2 in lines[0]:
cv2.line(small_frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.imshow("lines", small_frame)
except Exception:
continue
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
程序说明:
1 x, y = frame.shape[0:2]
small_frame = cv2.resize(frame, (int(y / 2), int(x / 2)))
gray = cv2.cvtColor(small_frame, cv2.COLOR_BGR2GRAY)
把图像缩放为原来四分之一并转化为灰度图,以减小计算量
2 edges = cv2.Canny(gray, 50, 120)
使用Canny函数提取边缘
3 lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 100, minLineLength, maxLineGap)
使用HoughLineP提取直线
参数说明:
参数1:要处理的二值图像
参数2:rho和theta,一般取值1和 np.pi / 180
参数3:阈值,低于该阈值会被忽略
参数4:最小直线长度,小于该长度会被忽略
参数5:最大线段间隙,大于该间隙会被认为是两条线
4 try:
for x1, y1, x2, y2 in lines[0]:
cv2.line(small_frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.imshow(“lines”, small_frame)
except Exception:
continue
画出并显示直线
上一步如果没有检测到直线,lines可能为None或空数组,这是进行数组操作就会报错。因此要使用异常处理语句,如果出现Exception(无论是类型错误还是数组错误),就continue,重新检测一轮