YOLOv8实战:手把手教你打造智能交通监控系统(附全流程代码)

张开发
2026/4/5 3:50:56 15 分钟阅读

分享文章

YOLOv8实战:手把手教你打造智能交通监控系统(附全流程代码)
1. 为什么选择YOLOv8做智能交通监控智能交通系统是现代城市管理的重要工具而车辆检测是其中最基础也最关键的环节。在众多目标检测算法中YOLOv8凭借其出色的实时性和准确率脱颖而出。我去年参与某城市智慧交通项目时对比测试了多种算法YOLOv8在1080p视频流上能达到120FPS的推理速度同时保持92%的mAP这对需要7×24小时运行的监控系统至关重要。YOLOv8相比前代主要有三大优势更轻量nano版本仅3.2MB适合部署在边缘设备更精准引入Anchor-Free设计和新的损失函数更易用Ultralytics提供的Python接口像搭积木一样简单提示实际项目中建议从YOLOv8n开始验证效果再根据需求升级到s/m/l版本。我在某工业园区项目中用YOLOv8s在 Jetson Xavier NX 上实现了40FPS的实时检测。2. 五分钟快速搭建开发环境2.1 创建Python隔离环境推荐使用conda管理环境避免依赖冲突conda create -n traffic-yolo python3.10 -y conda activate traffic-yolo2.2 安装核心依赖Ultralytics官方推荐用pip安装pip install ultralytics opencv-python如果使用GPU加速需要额外安装CUDA版的PyTorchpip install torch torchvision --extra-index-url https://download.pytorch.org/whl/cu1182.3 验证安装运行以下命令检查环境import torch print(torch.cuda.is_available()) # 应返回True from ultralytics import YOLO print(YOLO(yolov8n.pt).info()) # 显示模型信息3. 数据处理实战技巧3.1 获取交通监控数据集推荐使用UA-DETRAC数据集包含10万标注帧覆盖多种天气和光照条件提供车辆计数和轨迹标注# 数据集目录结构示例 dataset/ ├── images/ │ ├── train/ │ └── val/ └── labels/ ├── train/ └── val/3.2 制作YOLO格式标注监控视频通常用CVAT标注转换脚本示例import cv2 from xml.etree import ElementTree as ET def convert_cvat_to_yolo(xml_path, output_dir): tree ET.parse(xml_path) root tree.getroot() for image in root.findall(image): img_name image.get(name) img_w float(image.get(width)) img_h float(image.get(height)) with open(f{output_dir}/{img_name.split(.)[0]}.txt, w) as f: for box in image.findall(box): label box.get(label) x_center (float(box.get(xtl)) float(box.get(xbr))) / 2 / img_w y_center (float(box.get(ytl)) float(box.get(ybr))) / 2 / img_h width (float(box.get(xbr)) - float(box.get(xtl))) / img_w height (float(box.get(ybr)) - float(box.get(ytl))) / img_h f.write(f{CLASS_MAP[label]} {x_center} {y_center} {width} {height}\n)4. 模型训练与调优4.1 基础训练配置创建data.yaml文件train: dataset/images/train val: dataset/images/val names: 0: car 1: bus 2: truck启动训练model YOLO(yolov8n.yaml) results model.train( datadata.yaml, epochs100, imgsz640, batch16, device0 )4.2 提升精度的技巧数据增强添加mosaic和mixupaugment: True mosaic: 0.5 mixup: 0.2迁移学习加载预训练权重model YOLO(yolov8n.pt) # 加载官方预训练模型超参优化使用遗传算法results model.tune( datadata.yaml, iterations30, optimizerAdamW )5. 部署到监控系统5.1 实时视频流处理cap cv2.VideoCapture(rtsp://camera_feed) model YOLO(best.pt) while cap.isOpened(): ret, frame cap.read() if not ret: break results model(frame) annotated_frame results[0].plot() cv2.imshow(Traffic Monitor, annotated_frame) if cv2.waitKey(1) ord(q): break5.2 车流量统计实现class TrafficCounter: def __init__(self, line_y): self.line_y line_y self.vehicles set() def update(self, boxes): for box in boxes: x1, y1, x2, y2 box.xyxy[0] if y1 self.line_y y2 and box.id not in self.vehicles: self.vehicles.add(box.id) return len(self.vehicles)6. 性能优化经验6.1 模型量化model.export(formatonnx, dynamicTrue, simplifyTrue) !onnxruntime-tools quantize -m model.onnx -o model_quant.onnx6.2 TensorRT加速trtexec --onnxmodel.onnx --saveEnginemodel.engine \ --fp16 --workspace20486.3 多线程处理from threading import Thread from queue import Queue class ProcessingPipeline: def __init__(self): self.frame_queue Queue(maxsize30) self.result_queue Queue() def capture_thread(self): while True: ret, frame cap.read() self.frame_queue.put(frame) def infer_thread(self): while True: frame self.frame_queue.get() results model(frame) self.result_queue.put(results)在实际项目中这套方案将某路口摄像头的处理延迟从380ms降低到95ms。关键是要根据硬件配置选择合适的模型版本我测试过的各版本性能对比如下模型版本参数量GPU显存占用FPS (RTX 3090)YOLOv8n3.2M1.2GB320YOLOv8s11.4M2.1GB180YOLOv8m25.9M4.3GB95记得第一次部署时因为没做模型量化导致边缘设备内存溢出后来通过动态量化解决了这个问题。建议在开发初期就考虑部署环境避免后期返工。

更多文章