霍夫变换直线检测python代码
时间: 2023-10-19 16:36:05 浏览: 106
以下是使用OpenCV库实现霍夫变换直线检测的Python代码:
```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 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()
```
以上代码中,首先读取一张图片,将其转化为灰度图像,然后进行边缘检测。接着使用`cv2.HoughLines()`函数进行霍夫变换,得到直线参数。最后在原图像上绘制直线,并显示结果。
阅读全文