diff --git a/scripts/pose_processor_mediapipe.py b/scripts/pose_processor_mediapipe.py new file mode 100755 index 00000000..31fbf6c9 --- /dev/null +++ b/scripts/pose_processor_mediapipe.py @@ -0,0 +1,203 @@ +#!/opt/homebrew/bin/python3.11 +""" +MediaPipe Pose Processor - 高準確率人體姿勢檢測 + +使用 Google MediaPipe Pose 模型,提供更高的準確率。 + +相比 Apple Vision Pose: +- ✅ 準確率更高 +- ✅ 支持 33 個關鍵點 +- ✅ 支持遮擋和困難姿勢 + +輸出格式與 pose_processor.py 兼容。 + +Usage: + python pose_processor_mediapipe.py video_path output_path [--uuid UUID] +""" + +import json +import argparse +import math +import time +import os +import sys +import cv2 +import numpy as np +import mediapipe as mp + +# 33 個關鍵點名稱 (MediaPipe Pose) +KEYPOINT_NAMES = [ + "nose", "left_eye_inner", "left_eye", "left_eye_outer", + "right_eye_inner", "right_eye", "right_eye_outer", + "left_ear", "right_ear", "mouth_left", "mouth_right", + "left_shoulder", "right_shoulder", "left_elbow", "right_elbow", + "left_wrist", "right_wrist", "left_pinky", "right_pinky", + "left_index", "right_index", "left_thumb", "right_thumb", + "left_hip", "right_hip", "left_knee", "right_knee", + "left_ankle", "right_ankle", "left_heel", "right_heel", + "left_foot_index", "right_foot_index" +] + + +class MediaPipePoseProcessor: + def __init__(self, model_complexity: int = 2): + """ + 初始化 MediaPipe Pose + + Args: + model_complexity: 模型複雜度 (0, 1, 2) + 0 = 最快,準確率較低 + 1 = 平衡 + 2 = 最慢,準確率最高 + """ + self.mp_pose = mp.solutions.pose + self.pose = self.mp_pose.Pose( + static_image_mode=False, + model_complexity=model_complexity, + smooth_landmarks=True, + enable_segmentation=False, + min_detection_confidence=0.5, + min_tracking_confidence=0.5, + ) + self.mp_drawing = mp.solutions.drawing_utils + + def process_video(self, video_path: str, output_path: str, uuid: str = None): + """處理視頻""" + cap = cv2.VideoCapture(video_path) + + if not cap.isOpened(): + print(f"[ERROR] Cannot open video: {video_path}") + return + + fps = cap.get(cv2.CAP_PROP_FPS) + total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + + print(f"[MediaPipe Pose] Video: {video_path}") + print(f"[MediaPipe Pose] FPS: {fps}, Frames: {total_frames}, Size: {width}x{height}") + print(f"[MediaPipe Pose] Model complexity: {self.pose.model_complexity}") + + frames_data = [] + frame_idx = 0 + + start_time = time.time() + + while cap.isOpened(): + ret, frame = cap.read() + if not ret: + break + + # 轉換為 RGB + rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + + # 檢測姿勢 + results = self.pose.process(rgb_frame) + + if results.pose_landmarks: + # 提取關鍵點 + landmarks = results.pose_landmarks.landmark + + # 轉換為關鍵點列表 + keypoints = [] + for i, lm in enumerate(landmarks): + keypoint = { + "name": KEYPOINT_NAMES[i] if i < len(KEYPOINT_NAMES) else f"keypoint_{i}", + "x": int(lm.x * width), + "y": int(lm.y * height), + "z": float(lm.z), + "confidence": float(lm.visibility) + } + keypoints.append(keypoint) + + # 計算邊界框 + x_coords = [lm.x for lm in landmarks] + y_coords = [lm.y for lm in landmarks] + + x_min = int(min(x_coords) * width) + x_max = int(max(x_coords) * width) + y_min = int(min(y_coords) * height) + y_max = int(max(y_coords) * height) + + bbox = { + "x": x_min, + "y": y_min, + "width": x_max - x_min, + "height": y_max - y_min + } + + person = { + "person_id": 0, + "keypoints": keypoints, + "bbox": bbox + } + + frame_data = { + "frame": frame_idx, + "timestamp": frame_idx / fps, + "persons": [person] + } + + frames_data.append(frame_data) + else: + # 沒有檢測到姿勢 + frame_data = { + "frame": frame_idx, + "timestamp": frame_idx / fps, + "persons": [] + } + frames_data.append(frame_data) + + frame_idx += 1 + + # 進度報告 + if frame_idx % 100 == 0: + elapsed = time.time() - start_time + fps_processed = frame_idx / elapsed + print(f"[MediaPipe Pose] Progress: {frame_idx}/{total_frames} ({frame_idx/total_frames*100:.1f}%), {fps_processed:.1f} fps") + + cap.release() + + elapsed = time.time() - start_time + print(f"[MediaPipe Pose] Completed: {frame_idx} frames in {elapsed:.1f}s ({frame_idx/elapsed:.1f} fps)") + + # 統計 + frames_with_pose = sum(1 for f in frames_data if f["persons"]) + total_poses = sum(len(f["persons"]) for f in frames_data) + + print(f"[MediaPipe Pose] Frames with pose: {frames_with_pose}/{frame_idx} ({frames_with_pose/frame_idx*100:.1f}%)") + print(f"[MediaPipe Pose] Total poses: {total_poses}") + + # 構建輸出 + output = { + "frame_count": len(frames_data), + "fps": fps, + "total_poses": total_poses, + "frames": frames_data + } + + # 寫入文件 + output_tmp = output_path + ".tmp" + with open(output_tmp, "w") as f: + json.dump(output, f, indent=2) + + os.rename(output_tmp, output_path) + print(f"[MediaPipe Pose] Output: {output_path}") + + +def main(): + parser = argparse.ArgumentParser(description="MediaPipe Pose Processor") + parser.add_argument("video_path", help="Path to video file") + parser.add_argument("output_path", help="Path to output JSON file") + parser.add_argument("--uuid", help="Video UUID (optional)") + parser.add_argument("--model-complexity", type=int, default=2, choices=[0, 1, 2], + help="Model complexity: 0=fast, 1=balanced, 2=accurate (default: 2)") + + args = parser.parse_args() + + processor = MediaPipePoseProcessor(model_complexity=args.model_complexity) + processor.process_video(args.video_path, args.output_path, args.uuid) + + +if __name__ == "__main__": + main() diff --git a/src/core/processor/pose.rs b/src/core/processor/pose.rs index e6fdf39b..d0f09402 100644 --- a/src/core/processor/pose.rs +++ b/src/core/processor/pose.rs @@ -159,6 +159,45 @@ pub async fn process_pose( let executor = PythonExecutor::new()?; + // Check for MediaPipe Pose first (highest accuracy) + let mediapipe_script = executor.script_path("pose_processor_mediapipe.py"); + + if mediapipe_script.exists() { + tracing::info!("[POSE] Using MediaPipe Pose for interpolation (highest accuracy): {:?}", mediapipe_script); + + let mut args = vec![video_path.to_string(), output_path.to_string()]; + if let Some(u) = uuid { + args.push("--uuid".to_string()); + args.push(u.to_string()); + } + args.push("--model-complexity".to_string()); + args.push("2".to_string()); // Highest accuracy + + executor + .run_with_frames( + "pose_processor_mediapipe.py", + &[video_path, output_path], + uuid, + "POSE", + Some(POSE_TIMEOUT), + frames, + ) + .await + .with_context(|| format!("Failed to run MediaPipe Pose"))?; + + let json_str = std::fs::read_to_string(output_path) + .context("Failed to read MediaPipe POSE output")?; + let result: PoseResult = serde_json::from_str(&json_str) + .context("Failed to parse MediaPipe POSE output")?; + tracing::info!( + "[POSE] MediaPipe Pose interpolation completed: {} frames", + result.frames.len() + ); + return Ok(result); + } + + tracing::info!("[POSE] MediaPipe Pose not found, trying other processors"); + // Rust processor path (MOMENTRY_USE_RUST_PROCESSORS=1) if *USE_RUST_PROCESSORS { if let Some(rust_bin) = executor.rust_binary_path("rust_pose") { @@ -271,6 +310,46 @@ pub async fn process_pose( tracing::info!("[POSE] Starting pose estimation: {}", video_path); + // Check for MediaPipe Pose first (highest accuracy) + let mediapipe_script = executor.script_path("pose_processor_mediapipe.py"); + + if mediapipe_script.exists() { + tracing::info!("[POSE] Using MediaPipe Pose (highest accuracy): {:?}", mediapipe_script); + + let mut args = vec![video_path.to_string(), output_path.to_string()]; + if let Some(u) = uuid { + args.push("--uuid".to_string()); + args.push(u.to_string()); + } + args.push("--model-complexity".to_string()); + args.push("2".to_string()); // Highest accuracy + + executor + .run_with_frames( + "pose_processor_mediapipe.py", + &[video_path, output_path], + uuid, + "POSE", + Some(POSE_TIMEOUT), + frames, + ) + .await + .with_context(|| format!("Failed to run MediaPipe Pose"))?; + + let json_str = std::fs::read_to_string(output_path) + .context("Failed to read MediaPipe POSE output")?; + let result: PoseResult = serde_json::from_str(&json_str) + .context("Failed to parse MediaPipe POSE output")?; + tracing::info!( + "[POSE] MediaPipe Pose completed: {} frames, {} total poses", + result.frames.len(), + result.frames.iter().map(|f| f.persons.len()).sum::() + ); + return Ok(result); + } + + tracing::info!("[POSE] MediaPipe Pose not found, trying other processors"); + // Rust processor path (MOMENTRY_USE_RUST_PROCESSORS=1) if *USE_RUST_PROCESSORS { if let Some(rust_bin) = executor.rust_binary_path("rust_pose") { @@ -300,7 +379,7 @@ pub async fn process_pose( ); } - // Swift processor path (preferred over Python) + // Swift processor path (Apple Vision - faster but lower accuracy) let swift_pose_path = std::path::Path::new( "/Users/accusys/momentry_core/scripts/swift_processors/.build/release/swift_pose" );