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
| import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from typing import Tuple, List, Dict
class SeatbeltDetector(nn.Module): """ 安全带检测与误用识别框架 三阶段: 1. Local Predictor - 局部关键点预测 2. Global Assembler - 全局形状组装 3. Shape Modeling - 形状合理性建模 """ def __init__(self, config: dict): super().__init__() self.local_predictor = LocalPredictor( backbone='resnet18', num_keypoints=6 ) self.global_assembler = GlobalAssembler( num_control_points=8 ) self.shape_classifier = ShapeClassifier( num_classes=5 ) def forward(self, image: torch.Tensor) -> Dict: """ Args: image: (B, 3, H, W) 输入图像(可见光或红外) Returns: result: { 'keypoints': 安全带关键点, 'belt_mask': 安全带分割, 'usage_type': 使用状态分类, 'confidence': 检测置信度 } """ keypoints, heatmaps = self.local_predictor(image) belt_curve, control_points = self.global_assembler(keypoints, heatmaps) usage_type, confidence = self.shape_classifier(belt_curve, keypoints) return { 'keypoints': keypoints, 'belt_curve': belt_curve, 'usage_type': usage_type, 'confidence': confidence }
class LocalPredictor(nn.Module): """ 局部关键点预测器 检测安全带的6个关键点: 1. 左肩点 2. 右肩点(跨肩) 3. 左腰点 4. 右腰点(扣点) 5. 中间点(胸骨) 6. 斜跨点 """ def __init__(self, backbone: str = 'resnet18', num_keypoints: int = 6): super().__init__() if backbone == 'resnet18': self.backbone = nn.Sequential( nn.Conv2d(3, 64, 7, 2, 3), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.MaxPool2d(3, 2, 1), self._make_res_block(64, 64), self._make_res_block(64, 128, stride=2), self._make_res_block(128, 256, stride=2), self._make_res_block(256, 512, stride=2), ) self.feature_dim = 512 else: raise ValueError(f"Unsupported backbone: {backbone}") self.keypoint_head = nn.Sequential( nn.Conv2d(self.feature_dim, 256, 3, 1, 1), nn.ReLU(inplace=True), nn.Conv2d(256, 128, 3, 1, 1), nn.ReLU(inplace=True), nn.Conv2d(128, num_keypoints, 1), ) self.offset_head = nn.Conv2d(self.feature_dim, num_keypoints * 2, 1) self.num_keypoints = num_keypoints def forward(self, image: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Args: image: (B, 3, H, W) Returns: keypoints: (B, K, 2) 关键点坐标 heatmaps: (B, K, H', W') 热图 """ feat = self.backbone(image) heatmaps = self.keypoint_head(feat) offsets = self.offset_head(feat) keypoints = self._decode_keypoints(heatmaps, offsets) return keypoints, heatmaps def _decode_keypoints( self, heatmaps: torch.Tensor, offsets: torch.Tensor ) -> torch.Tensor: """ 从热图解码关键点坐标 Args: heatmaps: (B, K, H', W') offsets: (B, K*2, H', W') Returns: keypoints: (B, K, 2) """ B, K, H, W = heatmaps.shape heatmaps_flat = heatmaps.view(B, K, -1) max_indices = torch.argmax(heatmaps_flat, dim=2) xs = (max_indices % W).float() ys = (max_indices // W).float() offsets = offsets.view(B, K, 2, H, W) keypoints = torch.zeros(B, K, 2, device=heatmaps.device) for k in range(K): for b in range(B): x = xs[b, k].long() y = ys[b, k].long() keypoints[b, k, 0] = xs[b, k] + offsets[b, k, 0, y, x] keypoints[b, k, 1] = ys[b, k] + offsets[b, k, 1, y, x] keypoints[:, :, 0] = keypoints[:, :, 0] * (image.shape[3] / W) keypoints[:, :, 1] = keypoints[:, :, 1] * (image.shape[2] / H) return keypoints def _make_res_block(self, in_ch, out_ch, stride=1): """构建残差块""" return nn.Sequential( nn.Conv2d(in_ch, out_ch, 3, stride, 1), nn.BatchNorm2d(out_ch), nn.ReLU(inplace=True), nn.Conv2d(out_ch, out_ch, 3, 1, 1), nn.BatchNorm2d(out_ch), )
class GlobalAssembler(nn.Module): """ 全局组装器 将离散关键点组装成连续安全带曲线 """ def __init__(self, num_control_points: int = 8): super().__init__() self.num_control_points = num_control_points self.control_net = nn.Sequential( nn.Linear(12, 64), nn.ReLU(inplace=True), nn.Linear(64, 128), nn.ReLU(inplace=True), nn.Linear(128, num_control_points * 2), ) def forward( self, keypoints: torch.Tensor, heatmaps: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor]: """ Args: keypoints: (B, K, 2) 关键点 heatmaps: (B, K, H', W') 热图 Returns: belt_curve: (B, 100, 2) 安全带曲线点 control_points: (B, C, 2) 控制点 """ keypoints_flat = keypoints.view(keypoints.shape[0], -1) control_points = self.control_net(keypoints_flat) control_points = control_points.view(-1, self.num_control_points, 2) belt_curve = self._generate_bspline(control_points, num_points=100) return belt_curve, control_points def _generate_bspline( self, control_points: torch.Tensor, num_points: int = 100 ) -> torch.Tensor: """ 生成B样条曲线 Args: control_points: (B, C, 2) num_points: 曲线点数 Returns: curve: (B, num_points, 2) """ B, C, _ = control_points.shape t = torch.linspace(0, 1, num_points, device=control_points.device) curve = torch.zeros(B, num_points, 2, device=control_points.device) for i in range(num_points): seg_idx = int(t[i] * (C - 1)) seg_idx = min(seg_idx, C - 2) alpha = (t[i] * (C - 1)) - seg_idx curve[:, i, 0] = ( control_points[:, seg_idx, 0] * (1 - alpha) + control_points[:, seg_idx + 1, 0] * alpha ) curve[:, i, 1] = ( control_points[:, seg_idx, 1] * (1 - alpha) + control_points[:, seg_idx + 1, 1] * alpha ) return curve
class ShapeClassifier(nn.Module): """ 形状分类器 基于曲线形状判断安全带使用状态 """ def __init__(self, num_classes: int = 5): super().__init__() self.curve_encoder = nn.Sequential( nn.Linear(200, 128), nn.ReLU(inplace=True), nn.Linear(128, 64), nn.ReLU(inplace=True), ) self.classifier = nn.Sequential( nn.Linear(64 + 12, 32), nn.ReLU(inplace=True), nn.Linear(32, num_classes), ) self.num_classes = num_classes def forward( self, belt_curve: torch.Tensor, keypoints: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor]: """ Args: belt_curve: (B, 100, 2) keypoints: (B, 6, 2) Returns: usage_type: (B,) 使用状态分类 confidence: (B,) 置信度 """ curve_flat = belt_curve.view(belt_curve.shape[0], -1) curve_feat = self.curve_encoder(curve_flat) keypoints_flat = keypoints.view(keypoints.shape[0], -1) feat = torch.cat([curve_feat, keypoints_flat], dim=1) logits = self.classifier(feat) usage_type = torch.argmax(logits, dim=1) confidence = F.softmax(logits, dim=1).max(dim=1)[0] return usage_type, confidence
if __name__ == "__main__": model = SeatbeltDetector({}) model.eval() image = torch.randn(1, 3, 480, 640) with torch.no_grad(): result = model(image) print(f"关键点: {result['keypoints'].shape}") print(f"使用状态: {result['usage_type']}") print(f"置信度: {result['confidence']}")
|