YOLOv8交通目标检测实战:从BDD100K数据集下载到模型部署全流程指南

1次阅读
没有评论

共计 2753 个字符,预计需要花费 7 分钟才能阅读完成。

image.webp

背景与痛点

交通目标检测是智能交通系统的核心任务之一,但在实际应用中面临诸多挑战:

YOLOv8 交通目标检测实战:从 BDD100K 数据集下载到模型部署全流程指南

  • 小目标检测 :交通标志、行人等目标在远距离拍摄时可能仅占几个像素
  • 遮挡问题 :车辆相互遮挡、树木遮挡标志牌等情况普遍存在
  • 光照变化 :昼夜交替、天气变化导致图像质量差异大
  • 实时性要求 :道路监控通常需要 30FPS 以上的处理速度

数据集准备

主流数据集对比

  1. BDD100K
  2. 包含 10 万张道路场景图像
  3. 标注了车辆、行人、交通灯等 10 类目标
  4. 特点:场景多样,适合通用交通目标检测

  5. TT100K

  6. 专注交通标志检测
  7. 包含中国道路的 45 类标志
  8. 特点:专业性强,但样本量较小

  9. CCTSDB2017

  10. 国内交通标志数据集
  11. 包含 3 大类(禁令、警告、指示)和 58 小类
  12. 特点:本土化程度高,适合国内场景

格式转换脚本

BDD100K 原始标注为 JSON 格式,需转换为 YOLO 所需的 txt 格式。以下是转换脚本核心部分:

import json
import os

def convert_bdd_to_yolo(json_path, output_dir, class_map):
    """
    参数说明:json_path: BDD100K 标注文件路径
    output_dir: 输出目录
    class_map: 类别名称到 ID 的映射字典
    """
    with open(json_path) as f:
        data = json.load(f)

    for item in data:
        img_name = item['name']
        txt_name = os.path.splitext(img_name)[0] + '.txt'
        output_path = os.path.join(output_dir, txt_name)

        with open(output_path, 'w') as f_out:
            for label in item['labels']:
                if label['category'] in class_map:
                    # 转换为 YOLO 格式:class x_center y_center width height
                    x1, y1 = label['box2d']['x1'], label['box2d']['y1']
                    x2, y2 = label['box2d']['x2'], label['box2d']['y2']

                    width = item['attributes']['width']
                    height = item['attributes']['height']

                    x_center = ((x1 + x2) / 2) / width
                    y_center = ((y1 + y2) / 2) / height
                    box_width = (x2 - x1) / width
                    box_height = (y2 - y1) / height

                    f_out.write(f"{class_map[label['category']]} {x_center} {y_center} {box_width} {box_height}\n")

data.yaml 配置

train: ./images/train  # 训练集路径
val: ./images/val      # 验证集路径
test: ./images/test    # 测试集路径

# 类别数量和名称
nc: 10
names: ['person', 'rider', 'car', 'bus', 'truck', 'bike', 'motor', 'traffic light', 'traffic sign', 'train']

YOLOv8 模型训练

环境配置

  1. 创建 conda 环境:

    conda create -n yolov8 python=3.8
    conda activate yolov8

  2. 安装依赖:

    pip install ultralytics torch==1.12.1+cu113 torchvision==0.13.1+cu113 --extra-index-url https://download.pytorch.org/whl/cu113

训练命令

from ultralytics import YOLO

# 加载预训练模型
model = YOLO('yolov8n.pt')  # 可根据需求选择 n /s/m/l/ x 尺寸

# 开始训练
results = model.train(
    data='data.yaml',
    epochs=100,
    imgsz=640,
    batch=16,
    device='0',  # 使用 GPU 0
    optimizer='AdamW',
    lr0=0.001,
    augment=True
)

关键参数解析

  • imgsz:输入图像尺寸,交通场景建议 640×640
  • batch:根据显存调整,RTX 3090 可设 32-64
  • augment:自动启用 Mosaic 等数据增强
  • optimizer:小数据集推荐 AdamW,大数据集可用 SGD

模型优化与部署

量化压缩

model.export(format='onnx', dynamic=True, simplify=True)  # 导出动态尺寸 ONNX

TensorRT 加速

trtexec --onnx=yolov8n.onnx --saveEngine=yolov8n.engine --fp16

推理代码示例

import cv2
from ultralytics import YOLO

model = YOLO('yolov8n.engine', task='detect')  # 加载 TensorRT 模型

cap = cv2.VideoCapture('traffic.mp4')
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break

    results = model(frame, imgsz=640)
    annotated_frame = results[0].plot()

    cv2.imshow('Detection', annotated_frame)
    if cv2.waitKey(1) == ord('q'):
        break

避坑指南

类别不平衡处理

  1. 过采样少数类
  2. 使用 Focal Loss
  3. 调整分类权重:
    model.train(cls=torch.tensor([1.0, 1.5, 1.0, 2.0, ...]))  # 按类别频率设置 

数据增强策略

  • 晴天数据:增加雨雾模拟
  • 小目标:启用 Mosaic9 增强
  • 遮挡:随机擦除 (RandomErasing)

常见训练问题

  1. 损失不下降
  2. 检查标注质量
  3. 降低学习率
  4. 尝试更小的模型尺寸

  5. 显存不足

  6. 减小 batch size
  7. 使用梯度累积
  8. 尝试混合精度训练

性能对比

模型 mAP@0.5 FPS(640px) 参数量
YOLOv8n 0.62 120 3.2M
YOLOv8s 0.68 85 11.4M
YOLOv8m 0.73 52 26.2M

开放性问题

  1. 如何设计更适合交通场景的 Neck 结构?
  2. 在边缘设备部署时,如何平衡精度和速度?
  3. 对于极端光照条件,有哪些预处理方法能提升检测稳定性?

希望这篇指南能帮助你快速搭建交通目标检测系统。实际应用中建议从 YOLOv8n 开始,逐步迭代优化模型结构和参数配置。

正文完
 0
评论(没有评论)