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 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
| """ 安全带误用检测系统
架构: 1. 人体姿态估计:定位肩部、髋部关键点 2. 安全带分割:分割安全带区域 3. 关系推理:判断安全带与人体关系 4. 误用分类:分类误用类型
"""
import torch import torch.nn as nn import torch.nn.functional as F from typing import Dict, List, Tuple, Optional import numpy as np from dataclasses import dataclass from enum import Enum
class BeltMisuseType(Enum): """安全带误用类型""" CORRECT = "correct" SHOULDER_BEHIND = "shoulder_behind" SHOULDER_UNDERARM = "shoulder_underarm" LAP_TOO_LOOSE = "lap_too_loose" LAP_TOO_HIGH = "lap_too_high" TWISTED = "twisted" SHARED = "shared" NOT_WORN = "not_worn"
@dataclass class Keypoint: """关键点""" name: str x: float y: float confidence: float
class HumanPoseEstimator(nn.Module): """ 人体姿态估计器 使用轻量级网络定位关键点 """ def __init__( self, num_keypoints: int = 17, backbone: str = "mobilenetv3" ): super().__init__() if backbone == "mobilenetv3": from torchvision.models import mobilenet_v3_small self.backbone = mobilenet_v3_small(pretrained=True).features feature_dim = 576 else: raise ValueError(f"Unknown backbone: {backbone}") self.keypoint_head = nn.Sequential( nn.Conv2d(feature_dim, 256, 1), nn.BatchNorm2d(256), nn.ReLU(), nn.Conv2d(256, num_keypoints, 1) ) self.keypoint_names = [ 'nose', 'left_eye', 'right_eye', 'left_ear', 'right_ear', 'left_shoulder', 'right_shoulder', 'left_elbow', 'right_elbow', 'left_wrist', 'right_wrist', 'left_hip', 'right_hip', 'left_knee', 'right_knee', 'left_ankle', 'right_ankle' ] def forward( self, image: torch.Tensor ) -> Dict[str, torch.Tensor]: """ 前向传播 Args: image: 输入图像 Returns: output: { 'heatmaps': 关键点热图 [B, K, H', W'], 'keypoints': 关键点坐标 } """ features = self.backbone(image) heatmaps = self.keypoint_head(features) heatmaps = F.interpolate( heatmaps, size=(image.size(2), image.size(3)), mode='bilinear', align_corners=False ) return {'heatmaps': heatmaps} def decode_keypoints( self, heatmaps: torch.Tensor, threshold: float = 0.3 ) -> List[List[Keypoint]]: """ 解码关键点 Args: heatmaps: [B, K, H, W] threshold: 置信度阈值 Returns: keypoints: 每张图的关键点列表 """ batch_size = heatmaps.size(0) all_keypoints = [] for b in range(batch_size): keypoints = [] for k, name in enumerate(self.keypoint_names): heatmap = heatmaps[b, k] max_val = heatmap.max() if max_val > threshold: max_idx = heatmap.argmax() y = (max_idx // heatmap.size(1)).item() x = (max_idx % heatmap.size(1)).item() keypoints.append(Keypoint( name=name, x=x / heatmap.size(1), y=y / heatmap.size(0), confidence=max_val.item() )) all_keypoints.append(keypoints) return all_keypoints
class SeatbeltSegmentor(nn.Module): """ 安全带分割器 分割安全带区域 """ def __init__(self): super().__init__() self.encoder = nn.Sequential( nn.Conv2d(3, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(64, 128, 3, padding=1), nn.BatchNorm2d(128), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(128, 256, 3, padding=1), nn.BatchNorm2d(256), nn.ReLU(), nn.MaxPool2d(2) ) self.decoder = nn.Sequential( nn.ConvTranspose2d(256, 128, 2, stride=2), nn.BatchNorm2d(128), nn.ReLU(), nn.ConvTranspose2d(128, 64, 2, stride=2), nn.BatchNorm2d(64), nn.ReLU(), nn.ConvTranspose2d(64, 32, 2, stride=2), nn.BatchNorm2d(32), nn.ReLU(), nn.Conv2d(32, 3, 1) ) def forward(self, image: torch.Tensor) -> torch.Tensor: """ 前向传播 Args: image: [B, 3, H, W] Returns: segmentation: [B, 3, H, W] 分割结果 """ features = self.encoder(image) seg = self.decoder(features) return seg
class BeltMisuseClassifier(nn.Module): """ 安全带误用分类器 基于关键点和分割结果判断误用类型 """ def __init__( self, feature_dim: int = 256, num_classes: int = 8 ): super().__init__() self.keypoint_encoder = nn.Sequential( nn.Linear(17 * 3, 128), nn.ReLU(), nn.Linear(128, feature_dim) ) self.seg_encoder = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(3, feature_dim) ) self.classifier = nn.Sequential( nn.Linear(feature_dim * 2, feature_dim), nn.ReLU(), nn.Dropout(0.3), nn.Linear(feature_dim, num_classes) ) self.misuse_types = list(BeltMisuseType) def forward( self, keypoints: torch.Tensor, seg_features: torch.Tensor ) -> torch.Tensor: """ 前向传播 Args: keypoints: 关键点特征 seg_features: 分割特征 Returns: logits: [B, num_classes] """ kp_features = self.keypoint_encoder(keypoints) seg_feat = self.seg_encoder(seg_features) fused = torch.cat([kp_features, seg_feat], dim=-1) logits = self.classifier(fused) return logits
class BeltMisuseDetector(nn.Module): """ 完整的安全带误用检测系统 """ def __init__(self): super().__init__() self.pose_estimator = HumanPoseEstimator() self.segmentor = SeatbeltSegmentor() self.classifier = BeltMisuseClassifier() def forward( self, image: torch.Tensor ) -> Dict[str, torch.Tensor]: """ 前向传播 Args: image: [B, 3, H, W] Returns: output: { 'heatmaps': 关键点热图, 'segmentation': 分割结果, 'misuse_logits': 误用分类 } """ pose_output = self.pose_estimator(image) seg_output = self.segmentor(image) keypoints = self._extract_keypoints(pose_output['heatmaps']) misuse_logits = self.classifier(keypoints, seg_output) return { 'heatmaps': pose_output['heatmaps'], 'segmentation': seg_output, 'misuse_logits': misuse_logits } def _extract_keypoints(self, heatmaps: torch.Tensor) -> torch.Tensor: """提取关键点特征""" batch_size = heatmaps.size(0) num_keypoints = heatmaps.size(1) keypoints = [] for b in range(batch_size): kp_list = [] for k in range(num_keypoints): heatmap = heatmaps[b, k] max_val = heatmap.max() max_idx = heatmap.argmax() y = (max_idx // heatmap.size(1)).float() / heatmap.size(0) x = (max_idx % heatmap.size(1)).float() / heatmap.size(1) kp_list.extend([x.item(), y.item(), max_val.item()]) keypoints.append(kp_list) return torch.tensor(keypoints, device=heatmaps.device)
class BeltMisuseAnalyzer: """安全带误用分析器""" def __init__(self, model_path: str = None): self.model = BeltMisuseDetector() if model_path: self.model.load_state_dict(torch.load(model_path)) self.model.eval() def analyze( self, image: np.ndarray ) -> Dict: """ 分析安全带佩戴情况 Args: image: 输入图像 Returns: result: 分析结果 """ import cv2 img = cv2.resize(image, (224, 224)) img = img.astype(np.float32) / 255.0 img = (img - [0.485, 0.456, 0.406]) / [0.229, 0.224, 0.225] img = img.transpose(2, 0, 1) img = torch.from_numpy(img).unsqueeze(0) with torch.no_grad(): output = self.model(img) misuse_type = self.model.classifier.misuse_types[ output['misuse_logits'].argmax().item() ] confidence = torch.softmax(output['misuse_logits'], dim=-1).max().item() return { 'misuse_type': misuse_type.value, 'confidence': confidence, 'is_correct': misuse_type == BeltMisuseType.CORRECT }
class RuleBasedValidator: """基于规则的验证器""" def __init__(self): self.LEFT_SHOULDER = 5 self.RIGHT_SHOULDER = 6 self.LEFT_HIP = 11 self.RIGHT_HIP = 12 def validate( self, keypoints: List[Keypoint], segmentation: np.ndarray ) -> Dict: """ 规则验证 Args: keypoints: 关键点列表 segmentation: 分割结果 [H, W, 3] Returns: validation: 验证结果 """ left_shoulder = self._get_keypoint(keypoints, 'left_shoulder') right_shoulder = self._get_keypoint(keypoints, 'right_shoulder') left_hip = self._get_keypoint(keypoints, 'left_hip') right_hip = self._get_keypoint(keypoints, 'right_hip') if not all([left_shoulder, right_shoulder, left_hip, right_hip]): return {'valid': False, 'reason': 'keypoints_missing'} shoulder_belt = self._check_shoulder_belt( left_shoulder, right_shoulder, segmentation ) lap_belt = self._check_lap_belt( left_hip, right_hip, segmentation ) return { 'valid': True, 'shoulder_belt': shoulder_belt, 'lap_belt': lap_belt, 'overall': shoulder_belt['correct'] and lap_belt['correct'] } def _get_keypoint( self, keypoints: List[Keypoint], name: str ) -> Optional[Keypoint]: """获取关键点""" for kp in keypoints: if kp.name == name: return kp return None def _check_shoulder_belt( self, left_shoulder: Keypoint, right_shoulder: Keypoint, segmentation: np.ndarray ) -> Dict: """检查肩带""" H, W = segmentation.shape[:2] shoulder_x = int(right_shoulder.x * W) shoulder_y = int(right_shoulder.y * H) region = segmentation[ max(0, shoulder_y - 20):min(H, shoulder_y + 20), max(0, shoulder_x - 20):min(W, shoulder_x + 20) ] shoulder_belt_pixels = region[:, :, 1].sum() total_pixels = region.shape[0] * region.shape[1] has_shoulder_belt = shoulder_belt_pixels > total_pixels * 0.1 return { 'detected': has_shoulder_belt, 'correct': has_shoulder_belt } def _check_lap_belt( self, left_hip: Keypoint, right_hip: Keypoint, segmentation: np.ndarray ) -> Dict: """检查腰带""" H, W = segmentation.shape[:2] hip_y = int((left_hip.y + right_hip.y) / 2 * H) hip_x_start = int(min(left_hip.x, right_hip.x) * W) hip_x_end = int(max(left_hip.x, right_hip.x) * W) region = segmentation[ max(0, hip_y - 30):min(H, hip_y + 30), hip_x_start:hip_x_end ] lap_belt_pixels = region[:, :, 2].sum() total_pixels = region.shape[0] * region.shape[1] has_lap_belt = lap_belt_pixels > total_pixels * 0.1 return { 'detected': has_lap_belt, 'correct': has_lap_belt }
if __name__ == "__main__": model = BeltMisuseDetector() print("安全带误用检测模型架构:") print("- 人体姿态估计: MobileNetV3 + Keypoint Head") print("- 安全带分割: U-Net风格分割网络") print("- 误用分类: 关键点+分割特征融合") dummy_image = torch.randn(1, 3, 224, 224) with torch.no_grad(): output = model(dummy_image) print(f"\n输出:") print(f" 热图: {output['heatmaps'].shape}") print(f" 分割: {output['segmentation'].shape}") print(f" 分类: {output['misuse_logits'].shape}") misuse_type = model.classifier.misuse_types[ output['misuse_logits'].argmax().item() ] print(f"\n预测误用类型: {misuse_type.value}")
|