opencv-python 实现识别两条黄色的车道线,后输出两条车道线的中线和坐标,生成代码
时间: 2024-10-22 22:22:26 浏览: 76
在OpenCV-Python中实现识别车道线通常涉及几个步骤:首先,使用摄像头捕获图像;然后,对图像进行预处理,如灰度化、二值化和边缘检测;接下来,应用Hough变换找出可能的直线候选;最后,通过分析和过滤,确定哪两条是最符合车道线的,并计算它们的中线和坐标。
这里是一个简化的示例代码,使用了霍夫变换(HoughLinesP)来寻找车道线:
```python
import cv2
import numpy as np
def detect_lane_lines(image_path):
# 读取图像
img = cv2.imread(image_path)
# 转为灰度并二值化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
# 边缘检测
edges = cv2.Canny(binary, 50, 150)
# 应用霍夫变换寻找直线
rho = 1 # 选择单位长度下的角度间隔
theta = np.pi / 180 # 角度精度
threshold = 20 # 线段的最小长度
min_line_length = 40 # 最小线段长度
max_line_gap = 10 # 邻近线段的最大间隙
lines = cv2.HoughLinesP(edges, rho, theta, threshold, np.array([]), minLineLength=min_line_length, maxLineGap=max_line_gap)
# 提取和分析车道线
left_lines, right_lines = [], []
for line in lines:
x1, y1, x2, y2 = line[0]
# 检查是否接近水平(假设车道线近乎平行)
if abs(y2 - y1) < max_line_gap * 2:
slope = (y2 - y1) / (x2 - x1)
# 根据斜率判断哪边是左车道线
if slope > 0:
right_lines.append((line, slope))
else:
left_lines.append((line, slope))
# 计算并绘制中线
if len(left_lines) and len(right_lines):
mid_line = (left_lines[-1][0] + right_lines[-1][0]) // 2
mid_point = (mid_line[0][0], mid_line[0][1])
cv2.line(img, tuple(mid_point), (img.shape[1], mid_point[1]), color=(0, 255, 0), thickness=2)
return img, mid_point
# 使用函数并输出结果
image_path = "lane_image.jpg" # 替换为你需要处理的图片路径
output_img, mid_line_coords = detect_lane_lines(image_path)
cv2.imshow("Lane Detection", output_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
阅读全文