#!/usr/bin/env python3 """ eval/process_full_grid_to_gt.py Converts camxtime_evaluation_full_grid → camxtime_evaluation_gt. Generates GT videos for the 5 moving-camera patterns only (81 frames each). Input scene structure: {input}/scene_X/ camera_000.mp4 ... camera_080.mp4 120-frame videos (video frame 0 = trajectory key '2') camera_000.json ... camera_080.json per-camera trajectory JSONs Output scene structure: {output}/scene_X/ moving_forward.mp4 + .json + .txt moving_backward.mp4 + .json + .txt moving_zigzag.mp4 + .json + .txt moving_bullettime.mp4 + .json + .txt moving_slowmo.mp4 + .json + .txt camera_data.json (copied from src_cam/scene_X/camera_data.json) Usage (run from repo root): python eval/process_full_grid_to_gt.py \\ --input camxtime_evaluation_full_grid \\ --output camxtime_evaluation_gt \\ --src_cam evaluation_dataset/src_cam """ import os import json import argparse import subprocess import shutil import tempfile import multiprocessing from pathlib import Path from datetime import datetime from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed from tqdm import tqdm # ── Constants ────────────────────────────────────────────────────────────────── N_CAMS = 81 BULLET_FRAME = 40 TRAJ_KEY_OFFSET = 2 # video frame index 0 → trajectory JSON key '2' # ── Pattern definitions (moving-cam only) ───────────────────────────────────── def build_moving_patterns(): zigzag = list(range(41)) + list(range(39, -1, -1)) slowmo = [j // 2 for j in range(81)] return { "moving_forward": [(i, i) for i in range(N_CAMS)], "moving_backward": [(i, N_CAMS-1-i) for i in range(N_CAMS)], "moving_zigzag": [(i, zigzag[i]) for i in range(N_CAMS)], "moving_bullettime": [(i, BULLET_FRAME) for i in range(N_CAMS)], "moving_slowmo": [(i, slowmo[i]) for i in range(N_CAMS)], } # ── Load per-camera trajectories & intrinsics ───────────────────────────────── def load_camera_trajectories(scene_dir: Path, n_cams: int = N_CAMS): """Load camera poses for cameras 0..n_cams-1. Prefers the compressed camera_data.json produced by compress_full_grid_cameras.py (~0.3 MB vs ~7.7 MB of individual JSONs). Falls back to per-camera JSONs if absent. """ compressed = scene_dir / "camera_data.json" if compressed.exists(): with open(compressed) as f: d = json.load(f) K = d["intrinsics"]["K"] intrinsics = {"K": K, "fx": K[0][0], "fy": K[1][1], "cx": K[0][2], "cy": K[1][2]} # All frames of a camera share the same pose; replicate across all motion indices. trajectories = { cam_idx: {frame: d["cameras"][str(cam_idx)]["c2w"] for frame in range(N_CAMS)} for cam_idx in range(n_cams) } return trajectories, intrinsics # Fallback: read individual per-camera JSONs trajectories = {} intrinsics = None for cam_idx in range(n_cams): json_path = scene_dir / f"camera_{cam_idx:03d}.json" if not json_path.exists(): raise FileNotFoundError( f"Missing: {json_path}\n" f" Run eval/compress_full_grid_cameras.py first, or keep per-camera JSONs." ) with open(json_path) as f: d = json.load(f) if intrinsics is None: K = d["intrinsics"]["K"] intrinsics = {"K": K, "fx": K[0][0], "fy": K[1][1], "cx": K[0][2], "cy": K[1][2]} traj = {} for key, val in d["trajectory"].items(): traj[int(key) - TRAJ_KEY_OFFSET] = val["c2w"] trajectories[cam_idx] = traj return trajectories, intrinsics # ── Frame extraction ─────────────────────────────────────────────────────────── def _extract_one_camera(args): vid_path, out_cam_dir, max_frame = args Path(out_cam_dir).mkdir(parents=True, exist_ok=True) cmd = [ "ffmpeg", "-y", "-i", str(vid_path), "-frames:v", str(max_frame + 1), "-start_number", "0", "-q:v", "2", str(Path(out_cam_dir) / "frame_%04d.jpg"), ] result = subprocess.run(cmd, capture_output=True) if result.returncode != 0: raise RuntimeError( f"ffmpeg extraction failed for {Path(vid_path).name}:\n" f"{result.stderr.decode()[-400:]}" ) def extract_scene_frames(scene_dir, temp_dir, n_cams=N_CAMS, max_frame=N_CAMS-1, n_threads=8): tasks = [ (scene_dir / f"camera_{i:03d}.mp4", temp_dir / f"camera_{i:03d}", max_frame) for i in range(n_cams) ] corrupt = set() futures_map = {} with ThreadPoolExecutor(max_workers=n_threads) as pool: futures_map = {pool.submit(_extract_one_camera, t): i for i, t in enumerate(tasks)} for fut in as_completed(futures_map): cam_idx = futures_map[fut] try: fut.result() except RuntimeError as e: corrupt.add(cam_idx) print(f" WARNING: camera_{cam_idx:03d}.mp4 is corrupt — will substitute from neighbor") # Substitute corrupt cameras with frames from nearest valid neighbor if corrupt: for cam_idx in sorted(corrupt): # find nearest valid camera (search outward from cam_idx) neighbor = None for delta in range(1, n_cams): for sign in (1, -1): cand = cam_idx + sign * delta if 0 <= cand < n_cams and cand not in corrupt: neighbor = cand break if neighbor is not None: break if neighbor is None: raise RuntimeError(f"No valid neighbor found for camera_{cam_idx:03d}") src_dir = temp_dir / f"camera_{neighbor:03d}" dst_dir = temp_dir / f"camera_{cam_idx:03d}" dst_dir.mkdir(parents=True, exist_ok=True) for frame_file in src_dir.iterdir(): dst = dst_dir / frame_file.name if not dst.exists(): shutil.copy2(frame_file, dst) print(f" INFO: camera_{cam_idx:03d} substituted from camera_{neighbor:03d}") # ── Video assembly ───────────────────────────────────────────────────────────── def build_video(frame_paths, output_path, fps=30): list_file = str(output_path) + ".concat.txt" with open(list_file, "w") as f: for fp in frame_paths: f.write(f"file '{fp}'\nduration {1.0/fps}\n") if frame_paths: f.write(f"file '{frame_paths[-1]}'\n") cmd = [ "ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", list_file, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-r", str(fps), str(output_path), ] result = subprocess.run(cmd, capture_output=True) os.unlink(list_file) if result.returncode != 0: raise RuntimeError(f"ffmpeg assembly failed:\n{result.stderr.decode()[-400:]}") # ── Trajectory output ────────────────────────────────────────────────────────── def _invert_rigid(c2w): R = [[c2w[r][c] for c in range(3)] for r in range(3)] t = [c2w[r][3] for r in range(3)] Rt = [[R[c][r] for c in range(3)] for r in range(3)] nt = [-sum(Rt[r][c] * t[c] for c in range(3)) for r in range(3)] return [[Rt[0][0], Rt[0][1], Rt[0][2], nt[0]], [Rt[1][0], Rt[1][1], Rt[1][2], nt[1]], [Rt[2][0], Rt[2][1], Rt[2][2], nt[2]], [0.0, 0.0, 0.0, 1.0]] def save_trajectory(traj_seq, intrinsics, scene_name, pattern_name, out_json, out_txt, video_rel): traj_dict = { str(i): {"c2w": c2w, "w2c": _invert_rigid(c2w), "source_cam_idx": cam, "source_motion_frame": mot} for i, (c2w, cam, mot) in enumerate(traj_seq) } with open(out_json, "w") as f: json.dump({"video_path": video_rel, "timestamp": datetime.now().isoformat()[:19], "pattern": pattern_name, "intrinsics": intrinsics, "trajectory": traj_dict, "extras": {"scene_name": scene_name, "pattern": pattern_name, "frame_count": len(traj_seq)}}, f, indent=2) K = intrinsics["K"] lines = [ "# Camera metadata", f"video_path: {video_rel}", f"pattern: {pattern_name}", f"scene_name: {scene_name}", f"fx: {intrinsics['fx']}", f"fy: {intrinsics['fy']}", f"cx: {intrinsics['cx']}", f"cy: {intrinsics['cy']}", f"frame_count: {len(traj_seq)}", "", "[K]", f"{K[0][0]:.6f} {K[0][1]:.6f} {K[0][2]:.6f}", f"{K[1][0]:.6f} {K[1][1]:.6f} {K[1][2]:.6f}", f"{K[2][0]:.6f} {K[2][1]:.6f} {K[2][2]:.6f}", "", "[CAMERA_TRAJECTORY]", "# output_frame cam=source_cam_idx motion=motion_frame pos(x y z) rot(row0 row1 row2)", ] for i, (c2w, cam, mot) in enumerate(traj_seq): px, py, pz = c2w[0][3], c2w[1][3], c2w[2][3] r = [c2w[0][0], c2w[0][1], c2w[0][2], c2w[1][0], c2w[1][1], c2w[1][2], c2w[2][0], c2w[2][1], c2w[2][2]] lines.append(f"{i} cam={cam} motion={mot} " f"{px:.6f} {py:.6f} {pz:.6f} {' '.join(f'{v:.6f}' for v in r)}") Path(out_txt).write_text("\n".join(lines)) # ── Per-scene worker ─────────────────────────────────────────────────────────── def process_scene(args): import time scene_dir, out_dir, src_cam_dir, fps, n_threads = args scene_dir, out_dir, src_cam_dir = Path(scene_dir), Path(out_dir), Path(src_cam_dir) scene_name = scene_dir.name out_scene = out_dir / scene_name out_scene.mkdir(parents=True, exist_ok=True) t_start = time.time() trajectories, intrinsics = load_camera_trajectories(scene_dir) src_cam_json = src_cam_dir / scene_name / "camera_data.json" if src_cam_json.exists(): shutil.copy2(src_cam_json, out_scene / "camera_data.json") patterns = build_moving_patterns() if all((out_scene / f"{n}.mp4").exists() and (out_scene / f"{n}.json").exists() for n in patterns): return scene_name, "skipped", 0.0, 0, len(patterns) n_done = n_skip = 0 with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) extract_scene_frames(scene_dir, tmp_path, N_CAMS, N_CAMS - 1, n_threads) for pattern_name, frame_seq in patterns.items(): out_vid = out_scene / f"{pattern_name}.mp4" out_json = out_scene / f"{pattern_name}.json" out_txt = out_scene / f"{pattern_name}.txt" if out_vid.exists() and out_json.exists(): n_skip += 1 continue frame_paths, traj_seq = [], [] for cam_idx, motion_idx in frame_seq: fp = tmp_path / f"camera_{cam_idx:03d}" / f"frame_{motion_idx:04d}.jpg" if not fp.exists(): raise FileNotFoundError(f"Missing frame: {fp}") frame_paths.append(str(fp)) traj_seq.append((trajectories[cam_idx][motion_idx], cam_idx, motion_idx)) build_video(frame_paths, out_vid, fps) save_trajectory(traj_seq, intrinsics, scene_name, pattern_name, out_json, out_txt, out_vid.name) n_done += 1 return scene_name, "done", time.time() - t_start, n_done, n_skip # ── CLI ──────────────────────────────────────────────────────────────────────── def main(): parser = argparse.ArgumentParser( description="Generate moving-camera GT videos from camxtime_evaluation_full_grid." ) parser.add_argument("--input", required=True) parser.add_argument("--output", required=True) parser.add_argument("--src_cam", required=True, help="evaluation_dataset/src_cam folder") parser.add_argument("--fps", type=int, default=30) parser.add_argument("--scenes", nargs="+") parser.add_argument("--workers", type=int, default=max(1, multiprocessing.cpu_count() // 8)) parser.add_argument("--threads", type=int, default=8, help="ffmpeg threads per scene for frame extraction") args = parser.parse_args() input_dir = Path(args.input) output_dir = Path(args.output) output_dir.mkdir(parents=True, exist_ok=True) scenes = ([input_dir / s for s in args.scenes] if args.scenes else sorted(p for p in input_dir.iterdir() if p.is_dir())) print(f"CPUs: {multiprocessing.cpu_count()} | workers: {args.workers} " f"| threads/scene: {args.threads} | scenes: {len(scenes)}\n") tasks = [(s, output_dir, Path(args.src_cam), args.fps, args.threads) for s in scenes] n_done = n_skipped = n_errors = 0 with ProcessPoolExecutor(max_workers=args.workers) as pool: futures = {pool.submit(process_scene, t): Path(t[0]).name for t in tasks} with tqdm(total=len(futures), desc="Overall", unit="scene", dynamic_ncols=True) as pbar: for fut in as_completed(futures): name = futures[fut] try: _, status, elapsed, pdone, pskip = fut.result() if status == "skipped": n_skipped += 1 tqdm.write(f" SKIP {name:<12s} (all patterns exist)") else: n_done += 1 tqdm.write(f" OK {name:<12s} {elapsed:5.1f}s " f"patterns: {pdone} built, {pskip} skipped") except Exception as exc: n_errors += 1 tqdm.write(f" ERR {name:<12s} {exc}") pbar.set_postfix(done=n_done, skip=n_skipped, err=n_errors) pbar.update(1) print(f"\nFinished — {n_done} built, {n_skipped} skipped, {n_errors} errors") print(f"Output: {output_dir}") if __name__ == "__main__": main()