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
| """ 安全带关键点检测模型 检测安全带的几何位置判断是否正确佩戴 """
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): """ 安全带关键点检测器 检测关键点: - 肩带起点(D环位置) - 肩带肩部位置 - 肩带胸口位置 - 腰带左侧位置 - 腰带右侧位置 - 锁扣位置 """ NUM_KEYPOINTS = 6 KEYPOINT_NAMES = [ 'shoulder_anchor', 'shoulder_point', 'chest_point', 'lap_left', 'lap_right', 'buckle' ] def __init__( self, backbone: str = 'resnet18', pretrained: bool = True ): super().__init__() if backbone == 'resnet18': from torchvision.models import resnet18 self.backbone = resnet18(pretrained=pretrained) self.backbone.fc = nn.Identity() feature_dim = 512 elif backbone == 'mobilenetv3': from torchvision.models import mobilenet_v3_small self.backbone = mobilenet_v3_small(pretrained=pretrained) self.backbone.classifier = nn.Identity() feature_dim = 576 else: raise ValueError(f"Unknown backbone: {backbone}") self.keypoint_head = nn.Sequential( nn.Linear(feature_dim, 256), nn.ReLU(inplace=True), nn.Dropout(0.3), nn.Linear(256, self.NUM_KEYPOINTS * 2) ) self.visibility_head = nn.Sequential( nn.Linear(feature_dim, 128), nn.ReLU(inplace=True), nn.Linear(128, self.NUM_KEYPOINTS), nn.Sigmoid() ) def forward( self, x: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor]: """ Args: x: (batch, 3, H, W) Returns: keypoints: (batch, num_keypoints, 2) 归一化坐标 visibility: (batch, num_keypoints) 可见性概率 """ features = self.backbone(x) keypoints = self.keypoint_head(features) keypoints = keypoints.view(-1, self.NUM_KEYPOINTS, 2) keypoints = torch.sigmoid(keypoints) visibility = self.visibility_head(features) return keypoints, visibility def get_belt_geometry( self, keypoints: torch.Tensor, visibility: torch.Tensor, threshold: float = 0.5 ) -> Dict: """ 分析安全带几何关系 Args: keypoints: (batch, 6, 2) visibility: (batch, 6) threshold: 可见性阈值 Returns: geometry: 几何分析结果 """ batch_size = keypoints.shape[0] results = [] for b in range(batch_size): kpts = keypoints[b].cpu().numpy() vis = visibility[b].cpu().numpy() valid_mask = vis > threshold result = { 'keypoints': kpts, 'visibility': vis, 'valid_mask': valid_mask } if valid_mask[0] and valid_mask[1] and valid_mask[2]: shoulder_vec = kpts[1] - kpts[0] chest_vec = kpts[2] - kpts[1] angle = np.arctan2(shoulder_vec[1], shoulder_vec[0]) - \ np.arctan2(chest_vec[1], chest_vec[0]) result['shoulder_angle'] = np.degrees(angle) if valid_mask[3] and valid_mask[4]: lap_vec = kpts[4] - kpts[3] result['lap_angle'] = np.degrees(np.arctan2(lap_vec[1], lap_vec[0])) results.append(result) return results
class BeltMisuseClassifier(nn.Module): """ 安全带错误佩戴分类器 分类类型: 0: 正确佩戴 1: 肩带位置错误 2: 腰带位置错误 3: 安全带扭曲 4: 未系安全带 """ NUM_CLASSES = 5 CLASS_NAMES = [ 'correct', 'shoulder_misuse', 'lap_misuse', 'twisted', 'not_worn' ] def __init__( self, backbone: str = 'efficientnet_b0', pretrained: bool = True ): super().__init__() from torchvision.models import efficientnet_b0 self.backbone = efficientnet_b0(pretrained=pretrained) in_features = self.backbone.classifier[1].in_features self.backbone.classifier[1] = nn.Linear(in_features, self.NUM_CLASSES) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: (batch, 3, H, W) Returns: logits: (batch, num_classes) """ return self.backbone(x) def predict(self, x: torch.Tensor) -> Tuple[int, float]: """预测类别""" self.eval() with torch.no_grad(): logits = self.forward(x) probs = F.softmax(logits, dim=1) pred_class = torch.argmax(probs, dim=1) confidence = probs[0, pred_class] return pred_class.item(), confidence.item()
class BeltMisuseDetector: """ 安全带错误佩戴综合检测器 结合关键点检测和分类判断 """ def __init__( self, keypoint_model_path: str, classifier_model_path: str, device: str = 'cpu' ): """ Args: keypoint_model_path: 关键点模型路径 classifier_model_path: 分类模型路径 device: 设备 """ self.device = device self.keypoint_model = BeltKeypointDetector() self.keypoint_model.load_state_dict( torch.load(keypoint_model_path, map_location=device) ) self.keypoint_model.to(device) self.keypoint_model.eval() self.classifier = BeltMisuseClassifier() self.classifier.load_state_dict( torch.load(classifier_model_path, map_location=device) ) self.classifier.to(device) self.classifier.eval() self.input_size = (224, 224) def preprocess( self, image: np.ndarray ) -> torch.Tensor: """预处理图像""" import cv2 image = cv2.resize(image, self.input_size) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = image.astype(np.float32) / 255.0 mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) image = (image - mean) / std image = image.transpose(2, 0, 1) tensor = torch.from_numpy(image).unsqueeze(0).float() return tensor.to(self.device) def detect( self, image: np.ndarray ) -> Dict: """ 检测安全带佩戴状态 Args: image: 输入图像 Returns: result: 检测结果 """ tensor = self.preprocess(image) with torch.no_grad(): keypoints, visibility = self.keypoint_model(tensor) with torch.no_grad(): class_logits = self.classifier(tensor) class_probs = F.softmax(class_logits, dim=1) pred_class = torch.argmax(class_probs, dim=1).item() confidence = class_probs[0, pred_class].item() geometry = self.keypoint_model.get_belt_geometry(keypoints, visibility) rule_result = self._rule_based_check(keypoints[0].cpu().numpy(), visibility[0].cpu().numpy()) final_result = { 'classification': { 'class_id': pred_class, 'class_name': BeltMisuseClassifier.CLASS_NAMES[pred_class], 'confidence': confidence }, 'keypoints': { 'points': keypoints[0].cpu().numpy(), 'visibility': visibility[0].cpu().numpy(), 'geometry': geometry[0] }, 'rule_check': rule_result, 'is_correct': pred_class == 0 and rule_result['is_valid'] } return final_result def _rule_based_check( self, keypoints: np.ndarray, visibility: np.ndarray ) -> Dict: """ 基于规则的检查 Args: keypoints: (6, 2) 关键点坐标 visibility: (6,) 可见性 Returns: result: 规则检查结果 """ issues = [] if visibility[0] > 0.5 and visibility[1] > 0.5 and visibility[2] > 0.5: shoulder_vec = keypoints[1] - keypoints[0] chest_vec = keypoints[2] - keypoints[1] if shoulder_vec[1] < 0: issues.append('shoulder_belt_direction_wrong') angle = np.abs(np.arctan2(shoulder_vec[1], shoulder_vec[0])) if angle > np.radians(60): issues.append('shoulder_angle_abnormal') if visibility[3] > 0.5 and visibility[4] > 0.5: lap_vec = keypoints[4] - keypoints[3] lap_angle = np.abs(np.arctan2(lap_vec[1], lap_vec[0])) if lap_angle > np.radians(30): issues.append('lap_belt_not_horizontal') if visibility[1] > 0.5: if keypoints[1, 1] > 0.5: issues.append('shoulder_point_too_low') return { 'is_valid': len(issues) == 0, 'issues': issues }
if __name__ == "__main__": keypoint_model = BeltKeypointDetector(backbone='resnet18') classifier = BeltMisuseClassifier() x = torch.randn(2, 3, 224, 224) keypoints, visibility = keypoint_model(x) print("=== 关键点检测测试 ===") print(f"输入形状: {x.shape}") print(f"关键点形状: {keypoints.shape}") print(f"可见性形状: {visibility.shape}") logits = classifier(x) print("\n=== 分类测试 ===") print(f"输出形状: {logits.shape}") geometry = keypoint_model.get_belt_geometry(keypoints, visibility) print("\n=== 几何分析 ===") for i, g in enumerate(geometry): print(f"样本{i}: 有效关键点数={np.sum(g['valid_mask'])}") print(f"\n关键点模型参数: {sum(p.numel() for p in keypoint_model.parameters()):,}") print(f"分类模型参数: {sum(p.numel() for p in classifier.parameters()):,}")
|