利用cv2.HoughLines()函数实现霍夫变换检测直线,并把检测的直线绘制到图片内。
时间: 2023-08-14 13:07:33 浏览: 59
好的,以下是利用cv2.HoughLines()函数实现霍夫变换检测直线的代码示例:
```python
import cv2
import numpy as np
# 读取图片
img = cv2.imread('test.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)
# 绘制检测的直线
if lines is not None:
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('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
代码中,我们首先读取了一张图片,并将其转为灰度图,然后进行边缘检测。接着,我们调用cv2.HoughLines()函数进行霍夫变换检测直线,并将得到的直线绘制到原图上。最后,我们展示了处理后的图片,并等待用户按下任意键关闭窗口。
希望这个代码示例对你有帮助!