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
| """ 安全带错误佩戴检测模型 基于YOLOv8的关键点检测 + 状态分类 """
import torch import torch.nn as nn import torch.nn.functional as F from typing import Dict, List, Tuple, Optional import numpy as np
class BeltKeypointDetector(nn.Module): """ 安全带关键点检测器 检测安全带的路径关键点,用于判断佩戴状态 """ KEYPOINTS = [ "shoulder_anchor", "shoulder_point", "chest_point", "buckle_point", "hip_left", "hip_right" ] def __init__( self, backbone: str = "mobilenetv3", num_keypoints: int = 6 ): super().__init__() self.num_keypoints = num_keypoints if backbone == "mobilenetv3": from torchvision.models import mobilenet_v3_small base = mobilenet_v3_small(pretrained=True) self.backbone = nn.Sequential(*list(base.children())[:-1]) feature_dim = 576 else: raise ValueError(f"Unknown backbone: {backbone}") self.keypoint_head = nn.Sequential( nn.Conv2d(feature_dim, 256, 3, 1, 1), nn.BatchNorm2d(256), nn.ReLU(inplace=True), nn.Conv2d(256, num_keypoints * 3, 1) ) self.segment_head = nn.Sequential( nn.Conv2d(feature_dim, 128, 3, 1, 1), nn.BatchNorm2d(128), nn.ReLU(inplace=True), nn.Conv2d(128, 1, 1) ) def forward( self, x: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor]: """ Args: x: (batch, 3, H, W) Returns: keypoints: (batch, num_keypoints, 3) - x, y, confidence belt_mask: (batch, 1, H, W) """ batch_size = x.size(0) features = self.backbone(x) kpt_heatmap = self.keypoint_head(features) kpt_heatmap = kpt_heatmap.view(batch_size, self.num_keypoints, 3, -1) kpt_heatmap = kpt_heatmap.permute(0, 1, 3, 2) belt_mask = torch.sigmoid(self.segment_head(features)) return kpt_heatmap, belt_mask
class BeltMisuseClassifier(nn.Module): """ 安全带错误佩戴分类器 基于关键点位置判断佩戴状态 """ MISUSE_TYPES = [ "normal", "not_worn", "shoulder_behind", "under_arm", "loose_lap", "twisted", "multiple_users" ] def __init__( self, num_keypoints: int = 6 ): super().__init__() self.num_keypoints = num_keypoints self.classifier = nn.Sequential( nn.Linear(num_keypoints * 3, 128), nn.ReLU(inplace=True), nn.Dropout(0.3), nn.Linear(128, 64), nn.ReLU(inplace=True), nn.Linear(64, len(self.MISUSE_TYPES)) ) def forward( self, keypoints: torch.Tensor ) -> torch.Tensor: """ Args: keypoints: (batch, num_keypoints, 3) - x, y, confidence Returns: logits: (batch, num_classes) """ batch_size = keypoints.size(0) kpt_flat = keypoints.view(batch_size, -1) logits = self.classifier(kpt_flat) return logits def analyze_keypoints( self, keypoints: np.ndarray, image_size: Tuple[int, int] ) -> Dict: """ 分析关键点位置,判断错误类型 Args: keypoints: (num_keypoints, 3) - x, y, confidence image_size: (H, W) Returns: analysis: 分析结果 """ h, w = image_size kpt_normalized = keypoints.copy() kpt_normalized[:, 0] /= w kpt_normalized[:, 1] /= h shoulder_anchor = kpt_normalized[0, :2] shoulder_point = kpt_normalized[1, :2] chest_point = kpt_normalized[2, :2] buckle = kpt_normalized[3, :2] hip_left = kpt_normalized[4, :2] hip_right = kpt_normalized[5, :2] analysis = { "is_misuse": False, "misuse_type": "normal", "confidence": 0.0, "details": {} } if shoulder_point[0] < shoulder_anchor[0] - 0.1: analysis["is_misuse"] = True analysis["misuse_type"] = "shoulder_behind" analysis["details"]["shoulder_point_x"] = float(shoulder_point[0]) return analysis if shoulder_point[1] > shoulder_anchor[1] + 0.2: analysis["is_misuse"] = True analysis["misuse_type"] = "under_arm" analysis["details"]["shoulder_point_y"] = float(shoulder_point[1]) return analysis hip_center = (hip_left + hip_right) / 2 lap_distance = np.linalg.norm(hip_center - buckle) if lap_distance > 0.15: analysis["is_misuse"] = True analysis["misuse_type"] = "loose_lap" analysis["details"]["lap_distance"] = float(lap_distance) return analysis avg_confidence = np.mean(keypoints[:, 2]) if avg_confidence < 0.3: analysis["is_misuse"] = True analysis["misuse_type"] = "not_worn" analysis["details"]["avg_confidence"] = float(avg_confidence) return analysis analysis["confidence"] = float(avg_confidence) return analysis
class BeltMisuseDetector(nn.Module): """ 完整的安全带错误佩戴检测系统 """ def __init__( self, backbone: str = "mobilenetv3" ): super().__init__() self.keypoint_detector = BeltKeypointDetector(backbone) self.classifier = BeltMisuseClassifier() def forward( self, x: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Args: x: (batch, 3, H, W) Returns: keypoints: (batch, num_keypoints, 3) belt_mask: (batch, 1, H, W) class_logits: (batch, num_classes) """ keypoints, belt_mask = self.keypoint_detector(x) class_logits = self.classifier(keypoints) return keypoints, belt_mask, class_logits def detect( self, image: np.ndarray, conf_threshold: float = 0.5 ) -> Dict: """ 检测安全带状态 Args: image: 输入图像 conf_threshold: 置信度阈值 Returns: result: 检测结果 """ import cv2 original_size = image.shape[:2] input_tensor = self._preprocess(image) with torch.no_grad(): keypoints, belt_mask, logits = self.forward(input_tensor) keypoints_np = keypoints[0].cpu().numpy() class_probs = F.softmax(logits, dim=1)[0].cpu().numpy() analysis = self.classifier.analyze_keypoints( keypoints_np, (224, 224) ) predicted_class = np.argmax(class_probs) result = { "is_misuse": analysis["is_misuse"] or predicted_class > 0, "misuse_type": BeltMisuseClassifier.MISUSE_TYPES[predicted_class], "confidence": float(class_probs[predicted_class]), "keypoints": keypoints_np.tolist(), "class_probabilities": class_probs.tolist() } return result def _preprocess( self, image: np.ndarray, target_size: Tuple[int, int] = (224, 224) ) -> torch.Tensor: """图像预处理""" import cv2 image = cv2.resize(image, target_size) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = image.astype(np.float32) / 255.0 image = image.transpose(2, 0, 1) tensor = torch.from_numpy(image).unsqueeze(0) return tensor
if __name__ == "__main__": model = BeltMisuseDetector(backbone="mobilenetv3") x = torch.randn(1, 3, 224, 224) keypoints, belt_mask, logits = model(x) print("=== 安全带错误佩戴检测模型测试 ===") print(f"输入形状: {x.shape}") print(f"关键点输出: {keypoints.shape}") print(f"分割输出: {belt_mask.shape}") print(f"分类输出: {logits.shape}") print(f"参数量: {sum(p.numel() for p in model.parameters()):,}")
|