网站首页 > 技术文章 正文
以下是一个基于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 修改绘制的边界框颜色和粗细
该方案结合了深度学习的高精度目标检测和传统图像处理的高效特性,能够实时处理道路场景中的关键信息。用户可以根据实际场景需求调整参数以获得最佳效果。
猜你喜欢
- 2025-05-26 智能家居安防系统:AI与Python如何打造更安全的家
- 2025-05-26 在安卓设备上运行Python的方法
- 2025-05-26 基于OpenCv的人脸识别(Python完整代码)-大盘站
- 2025-05-26 边缘计算革命——Python在IoT与自动驾驶中的新战场
- 2025-05-26 还有这操作?我用Python这个库竟然实现了隔空操作
- 2025-05-26 一文带你深入了解Python+MediaPipe实现检测人脸的功能
- 2025-05-26 树莓派制成的 — 带运动检测和摄像头的安防系统
- 2025-05-26 用投影仪+摄像头DIY一台结构光3D扫描仪
- 2025-05-26 OpenCV-python 教你如何播放视频
- 2025-05-26 探索Python中的人脸识别:深入pyfacelib库
- 258℃Python短文,Python中的嵌套条件语句(六)
- 258℃python笔记:for循环嵌套。end=""的作用,图形打印
- 257℃PythonNet:实现Python与.Net代码相互调用!
- 252℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 251℃Python实现字符串小写转大写并写入文件
- 107℃原来2025是完美的平方年,一起探索六种平方的算吧
- 91℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 83℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)