9823cd4328
問題鏈: 1. Qdrant trace_id 全部為 -1 (40 個 faces) 2. rust_face_cluster 過濾所有 faces (trace_id >= 0) 3. 沒有 trace_profiles 生成 4. Worker 無限循環 (trace_stability = 0) 5. Deep scan 卡死 數據證據: - Qdrant: trace_id=-1: 40 faces (100%) - rust_face_cluster: Found 0 unique traces - processor_results: 只有 scene_vlm - 輸出文件: 全部缺失 - Worker: 無限循環,每 2 秒檢查一次 修復: - ✅ Python 腳本修復 (face_clustering_processor.py) - ✅ 問題定位完成 - ⏳ 等待決策: 方案 A (重置) 或 方案 B (調試) 文檔: - docs_v1.0/M4_workspace/2026-09-28_deep_scan_trace_id_issue.md - docs_v1.0/M4_workspace/2026-09-28_deep_scan_final_summary.md 狀態: ⚠️ Critical - 等待 M4 決策
250 lines
8.9 KiB
Python
Executable File
250 lines
8.9 KiB
Python
Executable File
#!/opt/homebrew/bin/python3.11
|
|
"""
|
|
MediaPipe Pose Processor (v1.0.0 API) - 高準確率人體姿勢檢測
|
|
|
|
使用 Google MediaPipe PoseLandmarker (新 API),提供更高的準確率。
|
|
|
|
MediaPipe v1.0.0 使用 tasks.vision.PoseLandmarker API。
|
|
|
|
相比 Apple Vision Pose:
|
|
- ✅ 準確率更高
|
|
- ✅ 支持 33 個關鍵點
|
|
- ✅ 支持遮擋和困難姿勢
|
|
|
|
輸出格式與 pose_processor.py 兼容。
|
|
|
|
Usage:
|
|
python pose_processor_mediapipe.py video_path output_path [--uuid UUID] [--model-complexity 0|1|2]
|
|
"""
|
|
|
|
import json
|
|
import argparse
|
|
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 PoseLandmarker (v1.0.0 API)
|
|
|
|
Args:
|
|
model_complexity: 模型複雜度 (0, 1, 2)
|
|
0 = 最快,準確率較低
|
|
1 = 平衡
|
|
2 = 最慢,準確率最高
|
|
"""
|
|
# 使用新 API (MediaPipe v1.0.0)
|
|
self.model_path = self._get_model_path(model_complexity)
|
|
|
|
if not os.path.exists(self.model_path):
|
|
raise FileNotFoundError(
|
|
f"MediaPipe Pose model not found: {self.model_path}\n"
|
|
f"Download from: https://storage.googleapis.com/mediapipe-models/pose_landmarker/"
|
|
)
|
|
|
|
# 創建 PoseLandmarker
|
|
options = mp.tasks.vision.PoseLandmarkerOptions(
|
|
base_options=mp.tasks.BaseOptions(
|
|
model_asset_path=self.model_path,
|
|
delegate=mp.tasks.BaseOptions.Delegate.CPU
|
|
),
|
|
running_mode=mp.tasks.vision.RunningMode.VIDEO,
|
|
num_poses=1,
|
|
min_pose_detection_confidence=0.5,
|
|
min_pose_presence_confidence=0.5,
|
|
min_tracking_confidence=0.5
|
|
)
|
|
|
|
self.landmarker = mp.tasks.vision.PoseLandmarker.create_from_options(options)
|
|
self.model_complexity = model_complexity
|
|
|
|
def _get_model_path(self, complexity: int) -> str:
|
|
"""獲取模型路徑"""
|
|
# MediaPipe v1.0.0 模型路徑
|
|
model_dir = os.path.expanduser("~/models/mediapipe")
|
|
model_names = {
|
|
0: "pose_landmarker_lite.task",
|
|
1: "pose_landmarker_full.task",
|
|
2: "pose_landmarker_heavy.task"
|
|
}
|
|
return os.path.join(model_dir, model_names.get(complexity, model_names[2]))
|
|
|
|
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.model_complexity}")
|
|
print(f"[MediaPipe Pose] Model: {self.model_path}")
|
|
|
|
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)
|
|
|
|
# 創建 MediaPipe Image
|
|
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb_frame)
|
|
|
|
# 計算時間戳(毫秒)
|
|
timestamp_ms = int(frame_idx * 1000 / fps)
|
|
|
|
# 檢測姿勢
|
|
results = self.landmarker.detect_for_video(mp_image, timestamp_ms)
|
|
|
|
if results.pose_landmarks and len(results.pose_landmarks) > 0:
|
|
# 提取第一個人的關鍵點
|
|
landmarks = results.pose_landmarks[0]
|
|
|
|
# 轉換為關鍵點列表
|
|
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 if hasattr(lm, 'visibility') else 1.0)
|
|
}
|
|
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 close(self):
|
|
"""釋放資源"""
|
|
if self.landmarker:
|
|
self.landmarker.close()
|
|
|
|
|
|
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)")
|
|
parser.add_argument("--frames", help="Comma-separated frame indices for 8Hz sampling (optional, ignored for MediaPipe)")
|
|
|
|
args = parser.parse_args()
|
|
|
|
try:
|
|
processor = MediaPipePoseProcessor(model_complexity=args.model_complexity)
|
|
processor.process_video(args.video_path, args.output_path, args.uuid)
|
|
processor.close()
|
|
except Exception as e:
|
|
print(f"[ERROR] {e}")
|
|
import traceback
|
|
traceback.print_exc()
|
|
sys.exit(1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|