您可以使用cv2.HoughLinesP()
检测线。查看结果底部。在其他图片上,它没有返回任何行。您的图片之间需要some一致性,因为您需要调整min_line_length
等。
import cv2
import matplotlib.pyplot as plt
import numpy as np
import math
img = cv2.imread('straight.jpg').astype(np.uint8)
m_list = list()
x_list = list()
y_list = list()
edges = cv2.Canny(img,50,150,apertureSize = 3)
lines = cv2.HoughLinesP(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 1, np.pi/360, 10,
minLineLength=30, maxLineGap=1)
if lines is not None:
for line in lines:
x1, y1, x2, y2 = np.maximum(1, line[0])
if x1 == x2:
x2 += 1
if y1 == y2:
y2 += 1
m = (y2 - y1) / (x2 - x1)
if not math.isinf(m):
m_list.append(m)
x_list.append([x1, x2])
y_list.append([y1, y2])
cv2.line(img, (x1, y1), (x2, y2), [122, 122, 255], 2)
print('{} lines identified.'.format(len(lines)))
else:
print('No lines identified.')
m_list = 0
x_list = 0
y_list = 0
plt.imshow(img)
plt.show()
1 lines identified.