import cv2
import numpy as np
# 加载图像
image = cv2.imread('image.jpg')
# 灰度转换
gray = cv2.cvtColor(image, 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 rho, theta in lines[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(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
# 显示结果
cv2.imshow('Hough Lines', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
在这个示例中,首先加载图像并将其转换为灰度图像。然后使用Canny边缘检测算法检测图像的边缘。接下来,使用cv2.HoughLines
函数执行霍夫直线变换,并设置了一些参数,例如距离分辨率、角度分辨率和阈值。最后,根据检测到的直线参数绘制直线,并显示结果图像。
结果如下:
import cv2
import numpy as np
img = cv2.imread('dave.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
minLineLength = 100
maxLineGap = 10
lines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength,maxLineGap)
for x1,y1,x2,y2 in lines[0]:
cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)
cv2.imwrite('houghlines5.jpg',img)
结果如下:
?