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
| import torch import torch.nn as nn import torch.nn.functional as F import numpy as np
class Cabin3DPoseEstimator(nn.Module): """ 座舱3D姿态估计 输入:RGB-D图像 输出:3D关键点坐标 """ KEYPOINTS = [ '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', 'head_top', 'neck', 'spine', 'pelvis' ] def __init__(self, num_keypoints: int = 21): super().__init__() self.rgb_encoder = nn.Sequential( nn.Conv2d(3, 64, 7, 2, 3), nn.BatchNorm2d(64), nn.ReLU(inplace=True), 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.depth_encoder = nn.Sequential( nn.Conv2d(1, 32, 7, 2, 3), nn.BatchNorm2d(32), nn.ReLU(inplace=True), self._make_res_block(32, 64), self._make_res_block(64, 128, stride=2), self._make_res_block(128, 256, stride=2), ) self.fusion = nn.Sequential( nn.Conv2d(512 + 256, 512, 3, 1, 1), nn.ReLU(inplace=True), ) self.heatmap_head = nn.Sequential( nn.Conv2d(512, 256, 3, 1, 1), nn.ReLU(inplace=True), nn.Conv2d(256, num_keypoints, 1), ) self.coord_3d_head = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(512, 512), nn.ReLU(inplace=True), nn.Linear(512, num_keypoints * 3), ) self.num_keypoints = num_keypoints def forward(self, rgb: torch.Tensor, depth: torch.Tensor) -> dict: """ Args: rgb: (B, 3, H, W) RGB图像 depth: (B, 1, H, W) 深度图 Returns: result: { 'keypoints_2d': (B, K, 2) 2D关键点, 'keypoints_3d': (B, K, 3) 3D关键点, 'heatmaps': (B, K, H', W') 热图 } """ rgb_feat = self.rgb_encoder(rgb) depth_feat = self.depth_encoder(depth) depth_feat = F.interpolate( depth_feat, size=rgb_feat.shape[-2:], mode='bilinear', align_corners=False ) fused = self.fusion(torch.cat([rgb_feat, depth_feat], dim=1)) heatmaps = self.heatmap_head(fused) keypoints_3d = self.coord_3d_head(fused) keypoints_3d = keypoints_3d.view(-1, self.num_keypoints, 3) keypoints_2d = self._decode_heatmaps(heatmaps) return { 'keypoints_2d': keypoints_2d, 'keypoints_3d': keypoints_3d, 'heatmaps': heatmaps } 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), nn.ReLU(inplace=True), ) def _decode_heatmaps(self, heatmaps: torch.Tensor) -> torch.Tensor: """从热图解码2D关键点""" 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() keypoints_2d = torch.stack([xs, ys], dim=2) return keypoints_2d
class OOPDetector: """ OOP异常姿态检测器 基于3D关键点判断异常姿态 """ NORMAL_CONSTRAINTS = { 'spine_angle': (150, 180), 'head_angle': (80, 100), 'shoulder_height_diff': 5, 'hip_angle': (90, 120), } def __init__(self, model_path: str): self.model = Cabin3DPoseEstimator() self.model.load_state_dict(torch.load(model_path)) self.model.eval() def detect_oop(self, rgb: np.ndarray, depth: np.ndarray) -> dict: """ 检测异常姿态 Args: rgb: RGB图像 depth: 深度图 Returns: result: { 'is_oop': 是否异常, 'oop_type': 异常类型, 'confidence': 置信度 } """ rgb_tensor = self._preprocess_rgb(rgb) depth_tensor = self._preprocess_depth(depth) with torch.no_grad(): result = self.model(rgb_tensor, depth_tensor) keypoints_3d = result['keypoints_3d'][0].cpu().numpy() oop_type = self._classify_oop(keypoints_3d) return { 'is_oop': oop_type is not None, 'oop_type': oop_type, 'confidence': result['heatmaps'].max().item() } def _classify_oop(self, keypoints: np.ndarray) -> str: """ 分类OOP类型 Args: keypoints: (K, 3) 3D关键点 Returns: oop_type: OOP类型或None """ features = self._extract_pose_features(keypoints) if features['spine_angle'] < self.NORMAL_CONSTRAINTS['spine_angle'][0]: return 'OOP-01' if features['shoulder_height_diff'] > self.NORMAL_CONSTRAINTS['shoulder_height_diff']: return 'OOP-02' if features['head_angle'] < self.NORMAL_CONSTRAINTS['head_angle'][0]: return 'OOP-03' return None def _extract_pose_features(self, keypoints: np.ndarray) -> dict: """提取姿态特征""" spine_vec = keypoints[18] - keypoints[19] spine_angle = np.arccos(spine_vec[1] / (np.linalg.norm(spine_vec) + 1e-8)) * 180 / np.pi head_vec = keypoints[17] - keypoints[18] head_angle = np.arccos(head_vec[1] / (np.linalg.norm(head_vec) + 1e-8)) * 180 / np.pi shoulder_diff = abs(keypoints[5, 1] - keypoints[6, 1]) return { 'spine_angle': spine_angle, 'head_angle': head_angle, 'shoulder_height_diff': shoulder_diff } def _preprocess_rgb(self, rgb: np.ndarray) -> torch.Tensor: x = rgb.astype(np.float32) / 255.0 x = (x - [0.485, 0.456, 0.406]) / [0.229, 0.224, 0.225] return torch.from_numpy(x).permute(2, 0, 1).unsqueeze(0) def _preprocess_depth(self, depth: np.ndarray) -> torch.Tensor: x = depth.astype(np.float32) / 1000.0 return torch.from_numpy(x).unsqueeze(0).unsqueeze(0)
if __name__ == "__main__": model = Cabin3DPoseEstimator() rgb = torch.randn(1, 3, 480, 640) depth = torch.randn(1, 1, 480, 640) result = model(rgb, depth) print(f"3D关键点: {result['keypoints_3d'].shape}") print(f"2D关键点: {result['keypoints_2d'].shape}")
|