用opencv写一个平行直线测距的python代码
时间: 2023-05-24 11:04:54 浏览: 141
以下是一个基于opencv的平行直线测距的python代码:
``` python
import cv2
import numpy as np
img = cv2.imread('input.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
lines = cv2.HoughLines(edges, 1, np.pi/180, 200)
for line in lines:
rho, theta = line[0]
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)
dist = abs(x1-x2)
print('Distance between lines: %d' % dist)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
本代码的输入图像应该是一张包含两个平行线的图片。代码使用Canny算子检测边缘,并使用霍夫变换检测直线。找到直线后,代码计算出它们之间的距离并将其输出。最后,代码读入并显示原始图像及标记的直线。
阅读全文