写一个用opencv做直线检测并且输出直线间角度的代码
时间: 2023-05-19 13:00:38 浏览: 199
以下是使用 OpenCV 进行直线检测并输出直线间角度的代码:
```python
import cv2
import numpy as np
# 读取图像
img = cv2.imread('image.jpg')
# 转换为灰度图像
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 i in range(len(lines)):
for j in range(i+1, len(lines)):
rho1, theta1 = lines[i][0]
rho2, theta2 = lines[j][0]
angle = abs(theta1 - theta2) * 180 / np.pi
print('Angle between line', i+1, 'and line', j+1, ':', angle)
# 绘制直线
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)
# 显示结果
cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这段代码可以读取一张图片,使用 Canny 边缘检测算法检测边缘,然后使用霍夫直线变换检测直线,并输出直线间的角度。最后,将检测到的直线绘制在原图上并显示结果。
阅读全文