#!/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()