1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
| import torch import torch.nn as nn
class YOLOSeatbeltDetector(nn.Module): """ YOLO + G-ELAN安全带检测 参考:Seatbelt and Mobile Usage Detection Using Deep Learning (Springer Nature, 2026) 精度:98%(安全带合规),99%(手机使用) 改进: - G-ELAN(Grouped Efficient Layer Aggregation Network) - 注意力机制增强小目标检测 """ def __init__(self, num_classes=6): super().__init__() self.backbone = CSPDarknet53() self.gelan = GELANModule( in_channels=256, out_channels=512, groups=4 ) self.attention = CBAMAttention(512) self.detector = nn.Sequential( nn.Conv2d(512, 256, 1), nn.BatchNorm2d(256), nn.ReLU(), nn.Conv2d(256, num_classes + 5, 1) ) def forward(self, x): """ Args: x: (B, 3, 640, 640) 输入图像 Returns: detections: (B, N, 11) 检测结果 - bbox: 4 (x, y, w, h) - conf: 1 - class: 6 (正常、腰带误用、斜带误用、扭曲、过松、儿童座椅不当) """ features = self.backbone(x) enhanced = self.gelan(features) weighted = self.attention(enhanced) detections = self.detector(weighted) return detections
class GELANModule(nn.Module): """ Grouped Efficient Layer Aggregation Network 改进自ELAN,增加分组卷积提升效率 结构: - 多分支卷积(不同扩张率) - 特征拼接 - 分组卷积融合 """ def __init__(self, in_channels, out_channels, groups=4): super().__init__() hidden_channels = out_channels // 2 self.branch1 = nn.Sequential( nn.Conv2d(in_channels, hidden_channels, 1), nn.BatchNorm2d(hidden_channels), nn.SiLU() ) self.branch2 = nn.Sequential( nn.Conv2d(hidden_channels, hidden_channels, 3, padding=1), nn.BatchNorm2d(hidden_channels), nn.SiLU() ) self.branch3 = nn.Sequential( nn.Conv2d(hidden_channels, hidden_channels, 3, padding=2, dilation=2), nn.BatchNorm2d(hidden_channels), nn.SiLU() ) self.branch4 = nn.Sequential( nn.Conv2d(hidden_channels, hidden_channels, 3, padding=3, dilation=3), nn.BatchNorm2d(hidden_channels), nn.SiLU() ) self.fusion = nn.Sequential( nn.Conv2d(hidden_channels * 4, out_channels, 1, groups=groups), nn.BatchNorm2d(out_channels), nn.SiLU() ) def forward(self, x): x1 = self.branch1(x) x2 = self.branch2(x1) x3 = self.branch3(x2) x4 = self.branch4(x3) concat = torch.cat([x1, x2, x3, x4], dim=1) out = self.fusion(concat) return out
class CBAMAttention(nn.Module): """ Convolutional Block Attention Module 通道注意力 + 空间注意力 增强安全带等细小目标的检测 """ def __init__(self, channels, reduction=16): super().__init__() self.channel_attention = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Conv2d(channels, channels // reduction, 1), nn.ReLU(), nn.Conv2d(channels // reduction, channels, 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) x = x * ca avg_pool = torch.mean(x, dim=1, keepdim=True) max_pool, _ = torch.max(x, dim=1, keepdim=True) sa_input = torch.cat([avg_pool, max_pool], dim=1) sa = self.spatial_attention(sa_input) x = x * sa return x
class SeatbeltMisuseDetector: """ IMS安全带误用检测系统 检测流程: 1. 图像采集(RGBIR摄像头) 2. 安全带定位 3. 误用分类 4. 警告触发 """ def __init__(self, model_path): self.model = YOLOSeatbeltDetector(num_classes=6) self.model.load_state_dict(torch.load(model_path)) self.model.eval() self.class_names = [ 'normal', 'lap_belt_high', 'shoulder_slip', 'belt_twisted', 'belt_loose', 'child_seat_error' ] self.warning_levels = { 0: 0, 1: 2, 2: 2, 3: 1, 4: 1, 5: 2 } def detect(self, image): """ 检测安全带误用 Args: image: (H, W, 3) RGB图像 Returns: result: dict - misuse_detected: bool - misuse_type: str - confidence: float - warning_level: int """ input_tensor = self.preprocess(image) with torch.no_grad(): detections = self.model(input_tensor) result = self.postprocess(detections) return result def preprocess(self, image): """ 图像预处理 标准化:归一化到[0, 1] 尺寸调整:640×640 """ image_norm = image / 255.0 import cv2 image_resized = cv2.resize(image_norm, (640, 640)) tensor = torch.FloatTensor(image_resized).permute(2, 0, 1).unsqueeze(0) return tensor def postprocess(self, detections): """ 后处理 解析检测结果 """ boxes, scores, classes = self.nms(detections) if len(boxes) > 0: max_idx = np.argmax(scores) class_id = int(classes[max_idx]) confidence = scores[max_idx] misuse_detected = class_id != 0 misuse_type = self.class_names[class_id] warning_level = self.warning_levels[class_id] return { 'misuse_detected': misuse_detected, 'misuse_type': misuse_type, 'confidence': confidence, 'warning_level': warning_level, 'bbox': boxes[max_idx].tolist() } else: return { 'misuse_detected': False, 'misuse_type': 'no_detection', 'confidence': 0.0, 'warning_level': 0, 'bbox': None } def nms(self, detections, iou_threshold=0.5, conf_threshold=0.5): """ 非极大值抑制 """ detections = detections.squeeze(0) mask = detections[:, 4] > conf_threshold detections = detections[mask] if len(detections) == 0: return [], [], [] boxes = detections[:, :4] scores = detections[:, 4] classes = detections[:, 5:].argmax(dim=1) return boxes.numpy(), scores.numpy(), classes.numpy()
def test_euro_ncap_seatbelt(): """ Euro NCAP安全带误用检测测试 """ detector = SeatbeltMisuseDetector('seatbelt_yolo_gelan.pth') image_sim = simulate_lap_belt_high() start_time = time.time() result = detector.detect(image_sim) detection_latency = time.time() - start_time print("\n" + "="*60) print("Euro NCAP BM-01测试(腰带位置过高)") print("="*60) print(f"\n误用检测: {result['misuse_detected']}") print(f"误用类型: {result['misuse_type']}") print(f"置信度: {result['confidence']:.2f}") print(f"警告等级: {result['warning_level']}") print(f"检测时延: {detection_latency*1000:.0f}ms") if result['misuse_detected'] and result['confidence'] > 0.7: if detection_latency <= 3: print("\n✓ Euro NCAP BM-01通过") else: print(f"\n✗ Euro NCAP BM-01未通过(时延>{detection_latency}秒)") else: print("\n✗ Euro NCAP BM-01未通过(检测失败)") print("="*60)
if __name__ == "__main__": test_euro_ncap_seatbelt()
|