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
| import numpy as np from typing import List, Dict, Tuple, Optional from dataclasses import dataclass from enum import Enum
class BodyPart(Enum): """身体部位枚举""" HEAD = 0 NECK = 1 RIGHT_SHOULDER = 2 RIGHT_ELBOW = 3 RIGHT_WRIST = 4 LEFT_SHOULDER = 5 LEFT_ELBOW = 6 LEFT_WRIST = 7 RIGHT_HIP = 8 RIGHT_KNEE = 9 RIGHT_ANKLE = 10 LEFT_HIP = 11 LEFT_KNEE = 12 LEFT_ANKLE = 13 CHEST = 14
@dataclass class Keypoint2D: """2D关键点""" body_part: BodyPart x: float y: float confidence: float
@dataclass class Keypoint3D: """3D关键点""" body_part: BodyPart x: float y: float z: float confidence: float
class OccupantPoseEstimator: """乘员姿态估计器""" def __init__(self, model_path: str, camera_intrinsics: np.ndarray): """ 初始化估计器 Args: model_path: 模型路径 camera_intrinsics: 相机内参矩阵 (3x3) """ self.keypoint_detector = self._load_keypoint_detector(model_path) self.depth_estimator = self._load_depth_estimator() self.camera_intrinsics = camera_intrinsics self.skeleton_template = self._load_skeleton_template() def estimate_pose(self, rgb_image: np.ndarray, depth_image: Optional[np.ndarray] = None) -> Dict: """ 估计乘员3D姿态 Args: rgb_image: RGB图像 depth_image: 深度图像(可选) Returns: result: { "keypoints_3d": List[Keypoint3D], "pose_type": str, "is_oop": bool, "confidence": float } """ keypoints_2d = self._detect_keypoints_2d(rgb_image) if depth_image is None: depth_map = self.depth_estimator.estimate(rgb_image) else: depth_map = depth_image keypoints_3d = self._backproject_to_3d(keypoints_2d, depth_map) keypoints_3d = self._apply_skeleton_constraints(keypoints_3d) pose_type = self._classify_pose(keypoints_3d) is_oop, confidence = self._detect_oop(keypoints_3d, pose_type) return { "keypoints_3d": keypoints_3d, "pose_type": pose_type, "is_oop": is_oop, "confidence": confidence } def _detect_keypoints_2d(self, rgb_image: np.ndarray) -> List[Keypoint2D]: """ 检测2D关键点 Args: rgb_image: RGB图像 Returns: keypoints_2d: 2D关键点列表 """ h, w = rgb_image.shape[:2] keypoints = [ Keypoint2D(BodyPart.HEAD, w * 0.5, h * 0.2, 0.95), Keypoint2D(BodyPart.NECK, w * 0.5, h * 0.3, 0.92), Keypoint2D(BodyPart.RIGHT_SHOULDER, w * 0.4, h * 0.35, 0.88), Keypoint2D(BodyPart.LEFT_SHOULDER, w * 0.6, h * 0.35, 0.87), Keypoint2D(BodyPart.CHEST, w * 0.5, h * 0.45, 0.85), Keypoint2D(BodyPart.RIGHT_HIP, w * 0.45, h * 0.6, 0.80), Keypoint2D(BodyPart.LEFT_HIP, w * 0.55, h * 0.6, 0.79), ] return keypoints def _backproject_to_3d(self, keypoints_2d: List[Keypoint2D], depth_map: np.ndarray) -> List[Keypoint3D]: """ 将2D关键点反投影到3D空间 Args: keypoints_2d: 2D关键点列表 depth_map: 深度图 Returns: keypoints_3d: 3D关键点列表 """ keypoints_3d = [] fx = self.camera_intrinsics[0, 0] fy = self.camera_intrinsics[1, 1] cx = self.camera_intrinsics[0, 2] cy = self.camera_intrinsics[1, 2] for kp2d in keypoints_2d: x_px = int(kp2d.x) y_px = int(kp2d.y) if 0 <= x_px < depth_map.shape[1] and 0 <= y_px < depth_map.shape[0]: z = depth_map[y_px, x_px] else: z = 1.0 x = (kp2d.x - cx) * z / fx y = (kp2d.y - cy) * z / fy keypoints_3d.append(Keypoint3D( body_part=kp2d.body_part, x=x, y=y, z=z, confidence=kp2d.confidence )) return keypoints_3d def _apply_skeleton_constraints(self, keypoints_3d: List[Keypoint3D]) -> List[Keypoint3D]: """ 应用骨骼约束优化3D姿态 骨骼长度约束、关节角度约束等 Args: keypoints_3d: 初始3D关键点 Returns: optimized_keypoints: 优化后的3D关键点 """ skeleton_connections = [ (BodyPart.HEAD, BodyPart.NECK), (BodyPart.NECK, BodyPart.RIGHT_SHOULDER), (BodyPart.NECK, BodyPart.LEFT_SHOULDER), (BodyPart.RIGHT_SHOULDER, BodyPart.RIGHT_ELBOW), (BodyPart.LEFT_SHOULDER, BodyPart.LEFT_ELBOW), (BodyPart.NECK, BodyPart.CHEST), (BodyPart.CHEST, BodyPart.RIGHT_HIP), (BodyPart.CHEST, BodyPart.LEFT_HIP), ] standard_lengths = self.skeleton_template return keypoints_3d def _classify_pose(self, keypoints_3d: List[Keypoint3D]) -> str: """ 分类姿态类型 Args: keypoints_3d: 3D关键点列表 Returns: pose_type: 姿态类型 """ positions = {kp.body_part: (kp.x, kp.y, kp.z) for kp in keypoints_3d} if BodyPart.HEAD in positions and BodyPart.CHEST in positions: head_pos = positions[BodyPart.HEAD] chest_pos = positions[BodyPart.CHEST] head_angle = np.arctan2( head_pos[0] - chest_pos[0], head_pos[2] - chest_pos[2] ) if abs(head_angle) < 0.3: return "normal" elif head_angle > 0.5: return "slouched" elif head_angle < -0.5: return "leaning_forward" if BodyPart.RIGHT_SHOULDER in positions and BodyPart.LEFT_SHOULDER in positions: right_shoulder = positions[BodyPart.RIGHT_SHOULDER] left_shoulder = positions[BodyPart.LEFT_SHOULDER] shoulder_diff = right_shoulder[0] - left_shoulder[0] if abs(shoulder_diff) > 0.2: return "leaning_sideways" return "unknown" def _detect_oop(self, keypoints_3d: List[Keypoint3D], pose_type: str) -> Tuple[bool, float]: """ 检测是否为OOP姿态 Args: keypoints_3d: 3D关键点列表 pose_type: 姿态类型 Returns: is_oop: 是否为OOP confidence: 置信度 """ oop_types = ["slouched", "leaning_forward", "leaning_sideways"] is_oop = pose_type in oop_types confidence = 0.8 if is_oop: avg_conf = np.mean([kp.confidence for kp in keypoints_3d]) confidence = min(avg_conf + 0.1, 1.0) return is_oop, confidence def _load_keypoint_detector(self, model_path: str): """加载关键点检测器""" return None def _load_depth_estimator(self): """加载深度估计器""" return DepthEstimator() def _load_skeleton_template(self) -> Dict: """加载标准骨骼模板""" return { (BodyPart.HEAD, BodyPart.NECK): 0.25, (BodyPart.NECK, BodyPart.RIGHT_SHOULDER): 0.20, (BodyPart.RIGHT_SHOULDER, BodyPart.RIGHT_ELBOW): 0.30, }
class DepthEstimator: """深度估计器""" def estimate(self, rgb_image: np.ndarray) -> np.ndarray: """ 从RGB图像估计深度 Args: rgb_image: RGB图像 Returns: depth_map: 深度图 """ h, w = rgb_image.shape[:2] depth_map = np.ones((h, w), dtype=np.float32) center_y, center_x = h // 2, w // 2 for y in range(h): for x in range(w): dist = np.sqrt((y - center_y)**2 + (x - center_x)**2) depth_map[y, x] = 0.8 + dist / max(h, w) * 0.5 return depth_map
if __name__ == "__main__": camera_intrinsics = np.array([ [500, 0, 320], [0, 500, 240], [0, 0, 1] ]) estimator = OccupantPoseEstimator("model_path", camera_intrinsics) rgb_image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) result = estimator.estimate_pose(rgb_image) print(f"姿态类型: {result['pose_type']}") print(f"是否OOP: {result['is_oop']}") print(f"置信度: {result['confidence']:.2f}") print(f"检测到 {len(result['keypoints_3d'])} 个3D关键点")
|