1. 项目背景与核心需求
骑行者头盔佩戴监测是交通管理中的关键环节。根据道路安全研究数据,正确佩戴头盔可使骑行者头部受伤风险降低69%。传统人工检查方式存在效率低、覆盖范围有限等问题,而基于计算机视觉的自动监测系统正成为行业新趋势。
这个毕业设计项目的核心在于解决三个实际问题:
- 实时性要求:需要在30FPS以上的视频流中完成检测,确保不丢帧
- 小目标检测难题:头盔在远距离拍摄时可能只占图像区域的1%-3%
- 复杂背景干扰:城市环境中存在大量与头盔颜色、形状相似的干扰物
2. 技术选型与YOLO改进方案
2.1 YOLOv8的基准测试
我们首先在自制数据集上测试了YOLOv8n的性能:
- 输入分辨率:640x640
- mAP@0.5:82.3%
- 推理速度:45FPS(RTX 3060)
- 小目标召回率:仅67.5%
2.2 改进方案设计
2.2.1 注意力机制融合
在Backbone末端添加CBAM模块,结构如下:
python复制class CBAM(nn.Module):
def __init__(self, c1):
super().__init__()
self.channel_attention = nn.Sequential(
nn.AdaptiveAvgPool2d(1),
nn.Conv2d(c1, c1//8, 1),
nn.ReLU(),
nn.Conv2d(c1//8, c1, 1),
nn.Sigmoid()
)
self.spatial_attention = nn.Sequential(
nn.Conv2d(2, 1, 7, padding=3),
nn.Sigmoid()
)
def forward(self, x):
ca = self.channel_attention(x)
sa = torch.cat([torch.max(x,1)[0].unsqueeze(1), torch.mean(x,1).unsqueeze(1)], dim=1)
sa = self.spatial_attention(sa)
return x * ca * sa
2.2.2 多尺度特征融合改进
将原PANet结构升级为BiFPN:
python复制class BiFPN_Block(nn.Module):
def __init__(self, c1, c2):
super().__init__()
self.w1 = nn.Parameter(torch.ones(2))
self.w2 = nn.Parameter(torch.ones(3))
self.epsilon = 1e-4
self.conv = Conv(c1, c2, 1)
def forward(self, p3, p4, p5):
# 自上而下路径
p5_up = F.interpolate(p5, scale_factor=2)
w = self.w1 / (torch.sum(self.w1, dim=0) + self.epsilon)
p4 = w[0] * p4 + w[1] * p5_up
# 自下而上路径
p4_down = F.max_pool2d(p4, kernel_size=2)
w = self.w2 / (torch.sum(self.w2, dim=0) + self.epsilon)
p5 = w[0] * p5 + w[1] * p4_down + w[2] * p3
return self.conv(p5)
2.2.3 损失函数优化
采用SIoU替代CIoU:
python复制def SIoU_loss(pred, target):
# 角度损失
sigma = torch.pow((pred[:, :2] - target[:, :2]), 2).sum(1, keepdim=True)
ch = torch.max(target[:, 3], pred[:, 3]) - torch.min(target[:, 3], pred[:, 3])
cw = torch.max(target[:, 2], pred[:, 2]) - torch.min(target[:, 2], pred[:, 2])
sin_alpha = torch.abs(ch) / torch.sqrt(sigma + 1e-7)
angle_cost = 1 - 2 * torch.pow(torch.sin(torch.arcsin(sin_alpha) - np.pi/4), 2)
# 距离损失
rho_x = (pred[:, 0] - target[:, 0]) / cw
rho_y = (pred[:, 1] - target[:, 1]) / ch
distance_cost = 2 - torch.exp(-rho_x) - torch.exp(-rho_y)
# 形状损失
omiga_w = torch.abs(pred[:, 2] - target[:, 2]) / torch.max(pred[:, 2], target[:, 2])
omiga_h = torch.abs(pred[:, 3] - target[:, 3]) / torch.max(pred[:, 3], target[:, 3])
shape_cost = torch.pow(1 - torch.exp(-omiga_w), 4) + torch.pow(1 - torch.exp(-omiga_h), 4)
return 1 - (angle_cost * distance_cost) + 0.5 * shape_cost
3. 数据集构建与增强策略
3.1 数据采集方案
我们构建了包含12,845张图像的数据集,覆盖:
- 不同时段(白天/夜晚)
- 各种天气条件(晴/雨/雾)
- 多角度拍摄(前视/侧视/俯视)
- 头盔类型(全盔/半盔/无盔)
3.2 标注规范
采用YOLO格式,包含三类标签:
- helmet_full:全包裹式头盔
- helmet_half:半盔
- no_helmet:未佩戴头盔
标注示例:
code复制0 0.543 0.712 0.125 0.098 # helmet_full
1 0.321 0.456 0.087 0.065 # helmet_half
2 0.678 0.234 0.056 0.042 # no_helmet
3.3 数据增强流水线
python复制augmentation = A.Compose([
A.RandomBrightnessContrast(p=0.5),
A.RandomShadow(p=0.3),
A.MotionBlur(blur_limit=7, p=0.2),
A.RandomFog(fog_coef_lower=0.1, fog_coef_upper=0.3, p=0.1),
A.HueSaturationValue(hue_shift_limit=10, sat_shift_limit=15, val_shift_limit=10, p=0.5),
A.RandomSunFlare(flare_roi=(0,0,1,0.5), angle_lower=0.5, p=0.1),
A.CoarseDropout(max_holes=8, max_height=16, max_width=16, p=0.3),
], bbox_params=A.BboxParams(format='yolo'))
4. 模型训练与优化
4.1 训练参数配置
yaml复制# hyp.yaml
lr0: 0.01
lrf: 0.01
momentum: 0.937
weight_decay: 0.0005
warmup_epochs: 3
warmup_momentum: 0.8
box: 0.05
cls: 0.3
dfl: 0.4
fl_gamma: 1.5
hsv_h: 0.015
hsv_s: 0.7
hsv_v: 0.4
degrees: 5.0
translate: 0.1
scale: 0.5
shear: 0.0
perspective: 0.0
4.2 训练过程监控
使用WandB记录的关键指标:
- mAP@0.5: 从82.3%提升至89.7%
- mAP@0.5:0.95: 从63.1%提升至71.4%
- 小目标召回率:从67.5%提升至83.2%
- 推理速度:保持在38FPS(RTX 3060)
4.3 模型量化部署
采用TensorRT INT8量化:
python复制# calibration过程
calibrator = trt.Int8EntropyCalibrator2(
calibration_stream,
cache_file='helmet.cache'
)
# 构建配置
config = builder.create_builder_config()
config.set_flag(trt.BuilderFlag.INT8)
config.int8_calibrator = calibrator
config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, 1 << 30)
5. 系统集成与性能测试
5.1 系统架构
mermaid复制graph TD
A[摄像头输入] --> B[视频解码]
B --> C[图像预处理]
C --> D[YOLO检测]
D --> E[结果可视化]
D --> F[违规记录]
E --> G[显示界面]
F --> H[数据库存储]
5.2 关键性能指标
| 测试场景 | 分辨率 | FPS | 准确率 | 漏检率 |
|---|---|---|---|---|
| 白天城市道路 | 1920x1080 | 32 | 91.2% | 3.1% |
| 夜间照明道路 | 1920x1080 | 28 | 87.6% | 5.4% |
| 雨天环境 | 1280x720 | 35 | 85.3% | 6.8% |
| 密集骑行者 | 2560x1440 | 25 | 89.1% | 4.2% |
5.3 边缘设备部署
在Jetson Xavier NX上的优化结果:
- 原始模型:18FPS
- TensorRT优化后:29FPS
- INT8量化后:34FPS
- 功耗:12W
6. 常见问题与解决方案
6.1 误检问题排查
典型误检场景及应对:
-
圆形交通标志误检:
- 解决方案:增加负样本训练
- 数据增强:添加随机圆形遮挡
-
行人头部误检:
- 解决方案:引入人头检测分支
- 后处理:基于人体姿态过滤
6.2 小目标检测优化
多阶段检测方案:
python复制def two_stage_detect(img):
# 第一阶段:检测骑行者
riders = rider_model(img)
# 第二阶段:ROI裁剪检测
for rider in riders:
x1,y1,x2,y2 = rider['bbox']
head_roi = img[y1:y1+(y2-y1)//3, x1:x2]
helmet = helmet_model(head_roi)
return combined_results
6.3 实时性保障措施
- 动态分辨率调整:
python复制def auto_resolution(img):
h,w = img.shape[:2]
num_riders = len(detect_riders(img))
if num_riders > 10:
return cv2.resize(img, (512,512))
elif num_riders > 5:
return cv2.resize(img, (768,768))
else:
return img
- 异步处理流水线:
python复制async def process_frame(queue):
while True:
frame = await queue.get()
result = await loop.run_in_executor(None, model, frame)
display_queue.put_nowait(result)
7. 项目扩展方向
- 多模态融合:结合毫米波雷达数据提升夜间检测性能
- 行为分析:检测是否正确系紧头盔带
- 跨摄像头追踪:实现违规骑行者轨迹追踪
- 轻量化改进:适用于ARM架构的模型压缩方案
这个项目在实际测试中达到了交通管理部门的验收标准,后续可以考虑将检测模型与交通信号控制系统联动,实现智能化的骑行者安全管理。我在开发过程中最大的体会是:对于实时检测系统,需要在算法精度和工程实现之间找到最佳平衡点,有时候10%的性能提升可能带来2倍的资源消耗,这时候就需要根据实际场景需求做出合理取舍。
