Python OpenCV 直线检测教程:使用 Hough 变换识别图像中的直线
以下是使用 OpenCV 库实现直线检测的 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)
# 绘制直线
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()
程序首先读取了一张图片,然后将其转换为灰度图像进行边缘检测。接着使用 Hough 变换进行直线检测,得到的结果是一系列直线的 rho 和 theta 参数。
最后将 rho 和 theta 转换为直线在图像上的两个端点,使用 cv2.line() 函数绘制直线。运行程序后,可以在窗口中看到检测结果。
原文地址: https://www.cveoy.top/t/topic/nDKU 著作权归作者所有。请勿转载和采集!