Python OpenCV 车道线检测代码
时间: 2023-11-05 16:57:13 浏览: 105
python+opencv车道线检测(简易实现)
以下是使用Python和OpenCV进行车道线检测的示例代码:
``` python
import cv2
import numpy as np
# 读取图像
image = cv2.imread('test.jpg')
# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# 高斯滤波
kernel_size = 5
blur_gray = cv2.GaussianBlur(gray, (kernel_size, kernel_size), 0)
# Canny边缘检测
low_threshold = 50
high_threshold = 150
edges = cv2.Canny(blur_gray, low_threshold, high_threshold)
# 区域选择
mask = np.zeros_like(edges)
ignore_mask_color = 255
imshape = image.shape
vertices = np.array([[(0,imshape[0]),(450, 325), (550, 325), (imshape[1],imshape[0])]], dtype=np.int32)
cv2.fillPoly(mask, vertices, ignore_mask_color)
masked_edges = cv2.bitwise_and(edges, mask)
# Hough变换
rho = 1
theta = np.pi/180
threshold = 20
min_line_length = 20
max_line_gap = 300
line_image = np.copy(image)*0
lines = cv2.HoughLinesP(masked_edges, rho, theta, threshold, np.array([]), min_line_length, max_line_gap)
# 绘制车道线
for line in lines:
for x1, y1, x2, y2 in line:
cv2.line(line_image, (x1, y1), (x2, y2), (255, 0, 0), 10)
# 将车道线绘制在原始图像上
color_edges = np.dstack((edges, edges, edges))
lines_edges = cv2.addWeighted(image, 0.8, line_image, 1, 0)
combo = cv2.addWeighted(color_edges, 0.2, lines_edges, 1, 0)
# 显示结果
cv2.imshow('result', combo)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,`test.jpg`是测试图像的文件名。在代码中,分别进行了图像读取、灰度化、高斯滤波、Canny边缘检测、区域选择、霍夫变换、车道线绘制等步骤。最终,将车道线绘制在原始图像上,并显示结果。
阅读全文