#!/usr/bin/env python3 """Render RoboTrack point annotations on top of their source videos. Expected layout: DATASET_ROOT/ clip_id/ video.mp4 point_tracks.npz Each NPZ must contain: trajs_2d: (frames, tracks, 2) pixel coordinates visibility: (frames, tracks) visibility scores query_frames: (tracks,) first/query frame for each track The default output is ``point_track_vis.mp4`` in each clip directory. Existing outputs are skipped unless ``--overwrite`` is supplied, so interrupted runs can be resumed safely. """ from __future__ import annotations import argparse import colorsys import os from concurrent.futures import ProcessPoolExecutor, as_completed from pathlib import Path import shutil import subprocess import sys import cv2 import numpy as np DEFAULT_FFMPEG_CANDIDATES = ( "/gpfs/projects/raivn/yunbos/.conda/envs/cotracker-perception/bin/ffmpeg", ) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("dataset_root", type=Path, help="RoboTrack dataset directory") parser.add_argument("--video-name", default="video.mp4") parser.add_argument("--tracks-name", default="point_tracks.npz") parser.add_argument("--output-name", default="point_track_vis.mp4") parser.add_argument( "--trail-seconds", type=float, default=1.0, help="Length of the visible motion trail (default: 1.0)", ) parser.add_argument( "--visibility-threshold", type=float, default=0.5, help="Scores above this value are drawn as visible (default: 0.5)", ) parser.add_argument( "--crf", type=int, default=20, help="H.264 quality: lower is better/larger (default: 20)", ) parser.add_argument( "--preset", default="veryfast", help="libx264 encoding preset (default: veryfast)", ) parser.add_argument( "--workers", type=int, default=min(4, os.cpu_count() or 1), help="Parallel clips to render (default: up to 4)", ) parser.add_argument( "--limit", type=int, help="Render only the first N clips (useful for testing)", ) parser.add_argument("--overwrite", action="store_true") parser.add_argument( "--ffmpeg", type=Path, help="Path to ffmpeg; otherwise resolve it automatically", ) return parser.parse_args() def find_ffmpeg(explicit_path: Path | None) -> str: if explicit_path is not None: if not explicit_path.is_file(): raise FileNotFoundError(f"ffmpeg does not exist: {explicit_path}") return str(explicit_path.resolve()) on_path = shutil.which("ffmpeg") if on_path: return on_path for candidate in DEFAULT_FFMPEG_CANDIDATES: if Path(candidate).is_file(): return candidate raise FileNotFoundError("Could not find ffmpeg; pass its path with --ffmpeg") def track_colors(count: int) -> list[tuple[int, int, int]]: """Return visually separated, stable BGR colors.""" colors = [] golden_ratio = 0.618033988749895 for index in range(count): hue = (0.07 + index * golden_ratio) % 1.0 red, green, blue = colorsys.hsv_to_rgb(hue, 0.88, 1.0) colors.append((round(blue * 255), round(green * 255), round(red * 255))) return colors def validate_tracks( npz_path: Path, ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: with np.load(npz_path) as data: required = {"trajs_2d", "visibility", "query_frames"} missing = required.difference(data.files) if missing: raise ValueError(f"missing NPZ arrays: {', '.join(sorted(missing))}") trajectories = np.asarray(data["trajs_2d"], dtype=np.float32) visibility = np.asarray(data["visibility"], dtype=np.float32) query_frames = np.asarray(data["query_frames"], dtype=np.int64) if trajectories.ndim != 3 or trajectories.shape[-1] != 2: raise ValueError(f"trajs_2d must have shape (T, N, 2), got {trajectories.shape}") if visibility.shape != trajectories.shape[:2]: raise ValueError( f"visibility shape {visibility.shape} does not match {trajectories.shape[:2]}" ) if query_frames.shape != (trajectories.shape[1],): raise ValueError( f"query_frames shape {query_frames.shape} does not match " f"({trajectories.shape[1]},)" ) if np.any(query_frames < 0) or np.any(query_frames >= trajectories.shape[0]): raise ValueError("query_frames contains an index outside the video") return trajectories, visibility, query_frames def visible_segments( points: np.ndarray, visible: np.ndarray ) -> list[np.ndarray]: """Split a short trajectory window into contiguous visible polylines.""" segments: list[np.ndarray] = [] start = None for index, is_visible in enumerate(visible): if is_visible and np.isfinite(points[index]).all(): if start is None: start = index elif start is not None: if index - start >= 2: segments.append(points[start:index]) start = None if start is not None and len(points) - start >= 2: segments.append(points[start:]) return segments def outlined_text( frame: np.ndarray, text: str, origin: tuple[int, int], font_scale: float, color: tuple[int, int, int], thickness: int, ) -> None: cv2.putText( frame, text, origin, cv2.FONT_HERSHEY_SIMPLEX, font_scale, (0, 0, 0), thickness + 3, cv2.LINE_AA, ) cv2.putText( frame, text, origin, cv2.FONT_HERSHEY_SIMPLEX, font_scale, color, thickness, cv2.LINE_AA, ) def fit_text_to_width( text: str, max_width: int, font_scale: float, thickness: int, ) -> str: """Elide the middle of text while preserving its identifying suffix.""" def width(candidate: str) -> int: size, _ = cv2.getTextSize( candidate, cv2.FONT_HERSHEY_SIMPLEX, font_scale, thickness ) return size[0] if width(text) <= max_width: return text for keep in range(len(text) - 1, 5, -1): prefix_length = (keep + 1) // 2 suffix_length = keep // 2 candidate = f"{text[:prefix_length]}...{text[-suffix_length:]}" if width(candidate) <= max_width: return candidate return "..." def draw_overlay( frame: np.ndarray, frame_index: int, trajectories: np.ndarray, visibility: np.ndarray, query_frames: np.ndarray, colors: list[tuple[int, int, int]], trail_frames: int, visibility_threshold: float, clip_id: str, ) -> np.ndarray: height, width = frame.shape[:2] num_frames, num_tracks = trajectories.shape[:2] visible_now = visibility[frame_index] > visibility_threshold visible_now &= query_frames <= frame_index point_radius = max(4, round(min(width, height) / 120)) point_outline = max(2, round(point_radius / 3)) trail_width = max(2, round(point_radius / 2)) font_scale = min(1.0, max(0.5, min(width, height) / 900)) font_thickness = max(1, round(font_scale * 2)) trail_layer = frame.copy() first_trail_frame = max(0, frame_index - trail_frames) for track_index in range(num_tracks): first = max(first_trail_frame, int(query_frames[track_index])) points = trajectories[first : frame_index + 1, track_index] visible = visibility[first : frame_index + 1, track_index] > visibility_threshold for segment in visible_segments(points, visible): rounded = np.rint(segment).astype(np.int32).reshape((-1, 1, 2)) cv2.polylines( trail_layer, [rounded], isClosed=False, color=colors[track_index], thickness=trail_width, lineType=cv2.LINE_AA, ) cv2.addWeighted(trail_layer, 0.72, frame, 0.28, 0.0, dst=frame) for track_index in range(num_tracks): if not visible_now[track_index]: continue point = trajectories[frame_index, track_index] if not np.isfinite(point).all(): continue x, y = np.rint(point).astype(int) # Coordinates just outside the image can occur in hand-authored tracks. # Clipping keeps the renderer robust while still placing a marker at the edge. x = int(np.clip(x, 0, width - 1)) y = int(np.clip(y, 0, height - 1)) if frame_index == int(query_frames[track_index]): cv2.circle( frame, (x, y), point_radius + point_outline + 3, (255, 255, 255), point_outline, cv2.LINE_AA, ) cv2.circle( frame, (x, y), point_radius + point_outline, (0, 0, 0), -1, cv2.LINE_AA, ) cv2.circle( frame, (x, y), point_radius, colors[track_index], -1, cv2.LINE_AA, ) label_x = min(width - 1, x + point_radius + 4) label_y = int(np.clip(y - point_radius - 2, 14, height - 2)) outlined_text( frame, str(track_index), (label_x, label_y), font_scale * 0.78, colors[track_index], font_thickness, ) active_count = int(np.count_nonzero(query_frames <= frame_index)) clip_line = fit_text_to_width( f"clip: {clip_id}", width - 20, font_scale, font_thickness ) stats_line = ( f"frame {frame_index + 1}/{num_frames} " f"visible {int(np.count_nonzero(visible_now))}/{active_count} " f"tracks {num_tracks}" ) clip_size, baseline = cv2.getTextSize( clip_line, cv2.FONT_HERSHEY_SIMPLEX, font_scale, font_thickness ) stats_size, _ = cv2.getTextSize( stats_line, cv2.FONT_HERSHEY_SIMPLEX, font_scale, font_thickness ) line_gap = max(5, round(font_scale * 6)) header_height = clip_size[1] + stats_size[1] + baseline + line_gap + 18 header_width = min(width, max(clip_size[0], stats_size[0]) + 20) header_layer = frame.copy() cv2.rectangle(header_layer, (0, 0), (header_width, header_height), (0, 0, 0), -1) cv2.addWeighted(header_layer, 0.62, frame, 0.38, 0.0, dst=frame) cv2.putText( frame, clip_line, (10, clip_size[1] + 7), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (255, 255, 255), font_thickness, cv2.LINE_AA, ) cv2.putText( frame, stats_line, (10, clip_size[1] + line_gap + stats_size[1] + 7), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (255, 255, 255), font_thickness, cv2.LINE_AA, ) return frame def render_clip( clip_dir_string: str, video_name: str, tracks_name: str, output_name: str, trail_seconds: float, visibility_threshold: float, crf: int, preset: str, ffmpeg: str, overwrite: bool, ) -> tuple[str, str, str]: clip_dir = Path(clip_dir_string) video_path = clip_dir / video_name tracks_path = clip_dir / tracks_name output_path = clip_dir / output_name clip_id = clip_dir.name if output_path.exists() and not overwrite: return clip_id, "skipped", "already exists" trajectories, visibility, query_frames = validate_tracks(tracks_path) capture = cv2.VideoCapture(str(video_path)) if not capture.isOpened(): raise RuntimeError(f"could not open video: {video_path}") width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = float(capture.get(cv2.CAP_PROP_FPS)) reported_frames = int(capture.get(cv2.CAP_PROP_FRAME_COUNT)) if width <= 0 or height <= 0 or fps <= 0: capture.release() raise ValueError(f"invalid video metadata: {width}x{height} at {fps} fps") if reported_frames > 0 and reported_frames != trajectories.shape[0]: capture.release() raise ValueError( f"video reports {reported_frames} frames but tracks have " f"{trajectories.shape[0]}" ) temporary_path = output_path.with_name( f".{output_path.stem}.tmp-{os.getpid()}{output_path.suffix}" ) command = [ ffmpeg, "-hide_banner", "-loglevel", "error", "-y", "-f", "rawvideo", "-pixel_format", "bgr24", "-video_size", f"{width}x{height}", "-framerate", f"{fps:.8f}", "-i", "-", "-an", "-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2", "-c:v", "libx264", "-preset", preset, "-crf", str(crf), "-pix_fmt", "yuv420p", "-movflags", "+faststart", str(temporary_path), ] encoder = subprocess.Popen( command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, ) frames_written = 0 colors = track_colors(trajectories.shape[1]) trail_frames = max(0, round(trail_seconds * fps)) failure: Exception | None = None try: assert encoder.stdin is not None for frame_index in range(trajectories.shape[0]): ok, frame = capture.read() if not ok: raise RuntimeError( f"video ended after {frames_written}/{trajectories.shape[0]} frames" ) draw_overlay( frame, frame_index, trajectories, visibility, query_frames, colors, trail_frames, visibility_threshold, clip_id, ) encoder.stdin.write(frame.tobytes()) frames_written += 1 except Exception as error: failure = error finally: capture.release() if encoder.stdin is not None: try: encoder.stdin.close() except BrokenPipeError: pass assert encoder.stderr is not None encoder_error = encoder.stderr.read().decode("utf-8", errors="replace").strip() return_code = encoder.wait() if failure is not None or return_code != 0: temporary_path.unlink(missing_ok=True) details = str(failure) if failure is not None else "" if encoder_error: details = f"{details}; ffmpeg: {encoder_error}".strip("; ") raise RuntimeError(details or f"ffmpeg exited with status {return_code}") if frames_written != trajectories.shape[0]: temporary_path.unlink(missing_ok=True) raise RuntimeError( f"wrote {frames_written} frames, expected {trajectories.shape[0]}" ) os.replace(temporary_path, output_path) return clip_id, "rendered", f"{frames_written} frames" def main() -> int: args = parse_args() dataset_root = args.dataset_root.resolve() if not dataset_root.is_dir(): print(f"error: dataset root does not exist: {dataset_root}", file=sys.stderr) return 2 if args.workers < 1: print("error: --workers must be at least 1", file=sys.stderr) return 2 if args.trail_seconds < 0: print("error: --trail-seconds cannot be negative", file=sys.stderr) return 2 if not 0 <= args.crf <= 51: print("error: --crf must be between 0 and 51", file=sys.stderr) return 2 try: ffmpeg = find_ffmpeg(args.ffmpeg) except FileNotFoundError as error: print(f"error: {error}", file=sys.stderr) return 2 clip_dirs = sorted( path for path in dataset_root.iterdir() if path.is_dir() and (path / args.video_name).is_file() and (path / args.tracks_name).is_file() ) if args.limit is not None: if args.limit < 0: print("error: --limit cannot be negative", file=sys.stderr) return 2 clip_dirs = clip_dirs[: args.limit] if not clip_dirs: print("No matching clip directories found.") return 0 print( f"Rendering {len(clip_dirs)} clips from {dataset_root} with " f"{args.workers} worker(s)", flush=True, ) print(f"ffmpeg: {ffmpeg}", flush=True) rendered = 0 skipped = 0 failures: list[tuple[str, str]] = [] common_args = ( args.video_name, args.tracks_name, args.output_name, args.trail_seconds, args.visibility_threshold, args.crf, args.preset, ffmpeg, args.overwrite, ) with ProcessPoolExecutor(max_workers=args.workers) as executor: future_to_clip = { executor.submit(render_clip, str(clip_dir), *common_args): clip_dir.name for clip_dir in clip_dirs } for completed, future in enumerate(as_completed(future_to_clip), start=1): clip_id = future_to_clip[future] try: _, status, detail = future.result() if status == "rendered": rendered += 1 else: skipped += 1 print( f"[{completed:>3}/{len(clip_dirs)}] {status:8} {clip_id} " f"({detail})", flush=True, ) except Exception as error: failures.append((clip_id, str(error))) print( f"[{completed:>3}/{len(clip_dirs)}] FAILED {clip_id}: {error}", file=sys.stderr, flush=True, ) print( f"Done: {rendered} rendered, {skipped} skipped, {len(failures)} failed.", flush=True, ) if failures: print("Failures:", file=sys.stderr) for clip_id, error in failures: print(f" {clip_id}: {error}", file=sys.stderr) return 1 return 0 if __name__ == "__main__": raise SystemExit(main())