"""Extract two persistent COCO-17 dancer tracks from the local reference clip. The copyrighted source video and source-overlay QA video remain local. The JSONL/NPZ annotations and skeleton-only visualizations are publishable derived research artifacts. """ from __future__ import annotations import argparse import hashlib from itertools import permutations import json from pathlib import Path import cv2 import numpy as np from ultralytics import YOLO JOINT_NAMES = ( "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", ) SKELETON_EDGES = ( (0, 1), (0, 2), (1, 3), (2, 4), (5, 6), (5, 7), (7, 9), (6, 8), (8, 10), (5, 11), (6, 12), (11, 12), (11, 13), (13, 15), (12, 14), (14, 16), ) TRACK_NAMES = ("locomotion_left_dancer", "expression_right_dancer") TRACK_COLORS = ((40, 220, 250), (238, 82, 170)) def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as source: for block in iter(lambda: source.read(1024 * 1024), b""): digest.update(block) return digest.hexdigest() def choose_candidates(result, frame_width: int, frame_height: int) -> list[dict]: if result.boxes is None or result.keypoints is None: return [] boxes = result.boxes.xyxy.detach().cpu().numpy() scores = result.boxes.conf.detach().cpu().numpy() keypoints = result.keypoints.data.detach().cpu().numpy() candidates = [] for box, score, joints in zip(boxes, scores, keypoints, strict=True): x1, y1, x2, y2 = (float(value) for value in box) width = max(0.0, x2 - x1) height = max(0.0, y2 - y1) if height < frame_height * 0.35 or width < frame_width * 0.04: continue candidates.append({ "box": np.array((x1, y1, x2, y2), dtype=np.float32), "score": float(score), "keypoints": joints.astype(np.float32), "center": np.array(((x1 + x2) * 0.5, (y1 + y2) * 0.5), dtype=np.float32), "quality": float(score * np.sqrt(width * height)), }) candidates.sort(key=lambda item: item["quality"], reverse=True) return candidates[:4] def assign_tracks(candidates: list[dict], previous: np.ndarray | None) -> list[dict | None]: if len(candidates) < 2: return [None, None] if previous is None or not np.isfinite(previous).all(): return sorted(candidates[:2], key=lambda item: float(item["center"][0])) best_cost = np.inf best = None for assignment in permutations(range(len(candidates)), 2): centers = np.stack([candidates[index]["center"] for index in assignment]) cost = float(np.linalg.norm(centers - previous, axis=1).sum()) if centers[0, 0] > centers[1, 0]: cost += 0.35 * abs(float(centers[0, 0] - centers[1, 0])) if cost < best_cost: best_cost = cost best = assignment assert best is not None return [candidates[best[0]], candidates[best[1]]] def draw_skeleton( image: np.ndarray, joints: np.ndarray, color: tuple[int, int, int], scale_xy: tuple[float, float] = (1.0, 1.0), ) -> None: sx, sy = scale_xy def point(index: int) -> tuple[int, int]: return (int(round(float(joints[index, 0]) * sx)), int(round(float(joints[index, 1]) * sy))) for start, end in SKELETON_EDGES: if joints[start, 2] >= 0.25 and joints[end, 2] >= 0.25: cv2.line(image, point(start), point(end), color, 4, cv2.LINE_AA) for index in range(len(JOINT_NAMES)): if joints[index, 2] >= 0.25: cv2.circle(image, point(index), 6, (255, 255, 255), -1, cv2.LINE_AA) cv2.circle(image, point(index), 4, color, -1, cv2.LINE_AA) def serialize_track(track: np.ndarray, box: np.ndarray, frame_width: int, frame_height: int) -> dict: return { "bbox_xyxy_px": [round(float(value), 3) for value in box], "joints": { name: { "x_px": round(float(track[index, 0]), 3), "y_px": round(float(track[index, 1]), 3), "x_norm": round(float(track[index, 0] / frame_width), 7), "y_norm": round(float(track[index, 1] / frame_height), 7), "confidence": round(float(track[index, 2]), 6), } for index, name in enumerate(JOINT_NAMES) }, } def run(args: argparse.Namespace) -> dict: video_path = args.video.resolve() output_dir = args.output.resolve() qa_dir = output_dir / "qa" examples_dir = output_dir / "examples" output_dir.mkdir(parents=True, exist_ok=True) qa_dir.mkdir(parents=True, exist_ok=True) examples_dir.mkdir(parents=True, exist_ok=True) capture = cv2.VideoCapture(str(video_path)) if not capture.isOpened(): raise RuntimeError(f"Could not open {video_path}") fps = float(capture.get(cv2.CAP_PROP_FPS)) frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT)) width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)) if fps <= 0 or frame_count <= 0 or width <= 0 or height <= 0: raise RuntimeError("Invalid video metadata") model = YOLO(args.model) fourcc = cv2.VideoWriter_fourcc(*"mp4v") overlay_path = qa_dir / "source_pose_overlay.mp4" skeleton_path = examples_dir / "skeleton_only.mp4" overlay_writer = cv2.VideoWriter(str(overlay_path), fourcc, fps, (width, height)) skeleton_size = (960, 540) skeleton_writer = cv2.VideoWriter(str(skeleton_path), fourcc, fps, skeleton_size) if not overlay_writer.isOpened() or not skeleton_writer.isOpened(): raise RuntimeError("Could not create QA video writers") all_keypoints = np.full((frame_count, 2, len(JOINT_NAMES), 3), np.nan, dtype=np.float32) all_boxes = np.full((frame_count, 2, 4), np.nan, dtype=np.float32) all_scores = np.full((frame_count, 2), np.nan, dtype=np.float32) valid = np.zeros((frame_count, 2), dtype=bool) previous_centers = None example_indices = set(np.linspace(0, frame_count - 1, 8, dtype=int).tolist()) records_path = output_dir / "human_pose_coco17.jsonl" with records_path.open("w", encoding="utf-8") as records: for frame_index in range(frame_count): ok, frame = capture.read() if not ok: all_keypoints = all_keypoints[:frame_index] all_boxes = all_boxes[:frame_index] all_scores = all_scores[:frame_index] valid = valid[:frame_index] frame_count = frame_index break result = model.predict( frame, imgsz=args.image_size, conf=args.confidence, device=args.device, verbose=False, )[0] tracks = assign_tracks(choose_candidates(result, width, height), previous_centers) current_centers = np.full((2, 2), np.nan, dtype=np.float32) record = {"frame_index": frame_index, "time_seconds": round(frame_index / fps, 7), "tracks": {}} overlay = frame.copy() skeleton = np.full((skeleton_size[1], skeleton_size[0], 3), (248, 249, 252), dtype=np.uint8) for track_index, track in enumerate(tracks): if track is None: continue joints = track["keypoints"] all_keypoints[frame_index, track_index] = joints all_boxes[frame_index, track_index] = track["box"] all_scores[frame_index, track_index] = track["score"] valid[frame_index, track_index] = True current_centers[track_index] = track["center"] color = TRACK_COLORS[track_index] draw_skeleton(overlay, joints, color) x1, y1, x2, y2 = (int(round(float(value))) for value in track["box"]) cv2.rectangle(overlay, (x1, y1), (x2, y2), color, 3) cv2.putText(overlay, TRACK_NAMES[track_index], (x1, max(28, y1 - 12)), cv2.FONT_HERSHEY_SIMPLEX, 0.75, color, 2, cv2.LINE_AA) draw_skeleton(skeleton, joints, color, (skeleton_size[0] / width, skeleton_size[1] / height)) record["tracks"][TRACK_NAMES[track_index]] = serialize_track(joints, track["box"], width, height) if np.isfinite(current_centers).all(): previous_centers = current_centers cv2.putText(skeleton, f"t={frame_index / fps:05.2f}s source-derived skeletons only", (24, 38), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (45, 51, 65), 2, cv2.LINE_AA) records.write(json.dumps(record, separators=(",", ":")) + "\n") overlay_writer.write(overlay) skeleton_writer.write(skeleton) if frame_index in example_indices: cv2.imwrite(str(examples_dir / f"skeleton_{frame_index:04d}.png"), skeleton) capture.release() overlay_writer.release() skeleton_writer.release() np.savez_compressed( output_dir / "human_pose_coco17.npz", keypoints_xyc=all_keypoints, bbox_xyxy=all_boxes, detector_confidence=all_scores, valid=valid, fps=np.array(fps), frame_width=np.array(width), frame_height=np.array(height), joint_names=np.array(JOINT_NAMES), track_names=np.array(TRACK_NAMES), ) detection_rate = valid.mean(axis=0) mean_joint_confidence = np.nanmean(all_keypoints[..., 2], axis=(0, 2)) summary = { "schema_version": "1.0", "source": { "youtube_url": "https://www.youtube.com/watch?v=dv2qKpna3lM", "clip_start_source_seconds": 103.0, "clip_end_source_seconds": 142.0, "source_file_sha256": sha256_file(video_path), "source_video_included_in_dataset": False, }, "video": {"frame_count": int(frame_count), "fps": fps, "duration_seconds": frame_count / fps, "width": width, "height": height}, "extractor": {"model": args.model, "image_size": args.image_size, "confidence_threshold": args.confidence, "device": args.device, "joint_schema": "COCO-17"}, "tracks": { TRACK_NAMES[index]: {"detection_rate": float(detection_rate[index]), "mean_joint_confidence": float(mean_joint_confidence[index])} for index in range(2) }, "files": {"jsonl": records_path.name, "npz": "human_pose_coco17.npz", "local_source_overlay": str(overlay_path.relative_to(output_dir)), "publishable_skeleton_video": str(skeleton_path.relative_to(output_dir))}, } (output_dir / "extraction_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8") print(json.dumps(summary, indent=2)) return summary def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("video", type=Path) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--model", default="yolo11n-pose.pt") parser.add_argument("--image-size", type=int, default=768) parser.add_argument("--confidence", type=float, default=0.25) parser.add_argument("--device", default="cpu") run(parser.parse_args()) if __name__ == "__main__": main()