Python实现YOLOv8车道线与车辆检测
以下是一个基于YOLOv8和OpenCV实现车道线与车辆检测的Python示例代码,结合了深度学习目标检测和传统图像处理技术:
python
import cv2
import numpy as np
from ultralytics import YOLO
def load_yolo_model():
# 加载预训练的YOLOv8模型
model = YOLO('yolov8n.pt') # 使用nano版本
return model
def detect_vehicles(frame, model):
# 使用YOLOv8进行车辆检测
results = model(frame, verbose=False)
# 解析检测结果
for result in results:
boxes = result.boxes.data.cpu().numpy()
for box in boxes:
x1, y1, x2, y2, conf, cls_id = box
if conf > 0.5 and cls_id in [2, 3, 5, 7]: # 车辆类别
cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
return frame
def detect_lanes(frame):
# 转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 高斯模糊降噪
blur = cv2.GaussianBlur(gray, (5, 5), 0)
# Canny边缘检测
edges = cv2.Canny(blur, 50, 150)
# 定义ROI区域(梯形区域)
height, width = edges.shape
mask = np.zeros_like(edges)
vertices = np.array([[
(width*0.1, height),
(width*0.45, height*0.6),
(width*0.55, height*0.6),
(width*0.9, height)
]], dtype=np.int32)
cv2.fillPoly(mask, vertices, 255)
masked_edges = cv2.bitwise_and(edges, mask)
# 霍夫变换检测直线
lines = cv2.HoughLinesP(masked_edges, 1, np.pi/180, 50,
minLineLength=50, maxLineGap=100)
# 过滤并绘制车道线
if lines is not None:
left_lines = []
right_lines = []
for line in lines:
x1, y1, x2, y2 = line[0]
slope = (y2 - y1) / (x2 - x1 + 1e-5)
if abs(slope) < 0.5: # 过滤水平线
continue
if slope < 0:
left_lines.append(line[0])
else:
right_lines.append(line[0])
# 平均车道线
def average_lines(lines):
if not lines:
return None
lines = np.array(lines)
return np.mean(lines, axis=0, dtype=np.int32)
avg_left = average_lines(left_lines)
avg_right = average_lines(right_lines)
# 绘制车道线
def draw_line(img, line, color=(0, 0, 255), thickness=10):
if line is not None:
x1, y1, x2, y2 = line
cv2.line(img, (x1, y1), (x2, y2), color, thickness)
draw_line(frame, avg_left)
draw_line(frame, avg_right)
return frame
def main():
# 初始化模型
model = load_yolo_model()
# 打开视频文件或摄像头
cap = cv2.VideoCapture('test_video.mp4') # 替换为你的视频路径
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# 车辆检测
vehicle_frame = detect_vehicles(frame.copy(), model)
# 车道线检测
lane_frame = detect_lanes(frame)
# 合并结果
combined = cv2.addWeighted(vehicle_frame, 0.8, lane_frame, 1, 0)
cv2.imshow('Lane and Vehicle Detection', combined)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
实现说明:
- 车辆检测部分:
O 使用YOLOv8的预训练模型进行目标检测
O 筛选车辆类别(包括汽车、卡车、公交车等)
O 在检测到车辆周围绘制边界框
- 车道线检测部分:
- 使用传统图像处理流程:
- 灰度转换
- 高斯模糊降噪
- Canny边缘检测
- ROI区域裁剪
- 霍夫变换检测直线
O 对检测到的直线进行过滤和平均处理
O 最终绘制稳定的左右车道线
- 性能优化建议:
O 调整ROI区域顶点坐标以适应不同视角
O 修改Canny和霍夫变换参数优化检测效果
O 使用GPU加速YOLO推理(安装CUDA版PyTorch)
O 降低视频处理分辨率提升速度
使用步骤:
- 安装依赖:
bash
pip install ultralytics opencv-python numpy
- 下载YOLOv8预训练模型(自动下载)或替换为自定义模型
- 准备测试视频(或将视频路径改为0使用摄像头)
- 运行脚本即可看到实时检测效果
参数调整建议:
- 车道线检测:
O 修改vertices数组调整ROI区域
O 调整Canny阈值(50, 150)
O 修改霍夫变换参数(阈值、最小线长等)
- 车辆检测:
O 调整置信度阈值(0.5)
O 修改绘制的边界框颜色和粗细
该方案结合了深度学习的高精度目标检测和传统图像处理的高效特性,能够实时处理道路场景中的关键信息。用户可以根据实际场景需求调整参数以获得最佳效果。