Download dynpose_eval/build_camera_controls.py from HugMinjun/geo4d_evals: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/datasets/HugMinjun/geo4d_evals/resolve/main/dynpose_eval/build_camera_controls.py
- Command line
-
hf download hf://datasets/HugMinjun/geo4d_evals/dynpose_eval/build_camera_controls.py
-
curl -L -o build_camera_controls.py https://huggingface.co/datasets/HugMinjun/geo4d_evals/resolve/main/dynpose_eval/build_camera_controls.py
15.2 kB
| """Build twelve NeoVerse-style camera controls for every DynPose scene. | |
| Each source keeps its original variable frame count. The relative trajectory | |
| is sampled over that count and composed frame-wise with the observed ViPE | |
| OpenCV c2w trajectory: | |
| target_c2w[t] = source_c2w[t] @ relative_c2w[t] | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from copy import deepcopy | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| from scipy.spatial.transform import Rotation, Slerp | |
| ROOT = Path(__file__).resolve().parent | |
| CONTROL_SPECS: dict[str, dict[str, float]] = { | |
| "pan_left": {"angle": 15.0}, | |
| "pan_right": {"angle": 15.0}, | |
| "tilt_up": {"angle": 15.0}, | |
| "tilt_down": {"angle": 15.0}, | |
| "move_left": {"distance": 0.1}, | |
| "move_right": {"distance": 0.1}, | |
| "push_in": {"distance": 0.1}, | |
| "pull_out": {"distance": 0.1}, | |
| "boom_up": {"distance": 0.1}, | |
| "boom_down": {"distance": 0.1}, | |
| "orbit_left": {"angle": 15.0, "orbit_radius": 1.0}, | |
| "orbit_right": {"angle": 15.0, "orbit_radius": 1.0}, | |
| } | |
| COMPOSITION = "target_c2w[t] = source_c2w[t] @ relative_c2w[t]" | |
| PROVENANCE = ( | |
| "NeoVerse CameraTrajectory.from_predefined defaults and dynamic-scene " | |
| "relative composition" | |
| ) | |
| def relative_endpoint(name: str, params: dict[str, float]) -> np.ndarray: | |
| """Match NeoVerse CameraTrajectory._get_camera_matrix exactly.""" | |
| angle = np.deg2rad(params.get("angle", 30.0)) | |
| radius = params.get("orbit_radius", 0.5) | |
| pose = np.eye(4, dtype=np.float64) | |
| if name == "move_left": | |
| pose[0, 3] = -params["distance"] | |
| elif name == "move_right": | |
| pose[0, 3] = params["distance"] | |
| elif name == "push_in": | |
| pose[2, 3] = params["distance"] | |
| elif name == "pull_out": | |
| pose[2, 3] = -params["distance"] | |
| elif name == "boom_up": | |
| pose[1, 3] = -params["distance"] | |
| elif name == "boom_down": | |
| pose[1, 3] = params["distance"] | |
| elif name in {"orbit_left", "orbit_right"}: | |
| theta = -angle if name == "orbit_left" else angle | |
| cosine, sine = np.cos(theta), np.sin(theta) | |
| pose[0, 3] = radius * sine | |
| pose[2, 3] = radius * (1.0 - cosine) | |
| pose[0, 0] = cosine | |
| pose[0, 2] = -sine | |
| pose[2, 0] = sine | |
| pose[2, 2] = cosine | |
| elif name in {"pan_left", "pan_right"}: | |
| theta = -angle if name == "pan_left" else angle | |
| cosine, sine = np.cos(theta), np.sin(theta) | |
| pose[0, 0] = cosine | |
| pose[0, 2] = sine | |
| pose[2, 0] = -sine | |
| pose[2, 2] = cosine | |
| elif name in {"tilt_up", "tilt_down"}: | |
| theta = angle if name == "tilt_up" else -angle | |
| cosine, sine = np.cos(theta), np.sin(theta) | |
| pose[1, 1] = cosine | |
| pose[1, 2] = -sine | |
| pose[2, 1] = sine | |
| pose[2, 2] = cosine | |
| else: | |
| raise ValueError(f"unsupported control: {name}") | |
| return pose | |
| def relative_trajectory(name: str, params: dict[str, float], num_frames: int) -> np.ndarray: | |
| endpoint = relative_endpoint(name, params) | |
| frame_times = np.linspace(0.0, 1.0, num_frames) | |
| rotations = Slerp( | |
| [0.0, 1.0], | |
| Rotation.from_matrix(np.stack([np.eye(3), endpoint[:3, :3]])), | |
| )(frame_times).as_matrix() | |
| positions = frame_times[:, None] * endpoint[:3, 3][None] | |
| output = np.repeat(np.eye(4, dtype=np.float64)[None], num_frames, axis=0) | |
| output[:, :3, :3] = rotations | |
| output[:, :3, 3] = positions | |
| return output | |
| def trajectory_template(name: str, params: dict[str, float]) -> dict[str, Any]: | |
| json_params = { | |
| key: int(value) if float(value).is_integer() else value | |
| for key, value in params.items() | |
| } | |
| return { | |
| "name": name, | |
| "description": f"NeoVerse predefined {name} control for variable-length DynPose clips", | |
| "mode": "relative", | |
| "num_frames_rule": "match_source_num_frames", | |
| "zoom_ratio": 1.0, | |
| "use_first_frame": True, | |
| "composition": COMPOSITION, | |
| "interpolation": {"rotation": "Slerp", "translation": "linear"}, | |
| "normalized_keyframes": [ | |
| {"time": 0.0, "operations": [{"static": {}}]}, | |
| {"time": 1.0, "operations": [{name: json_params}]}, | |
| ], | |
| } | |
| def source_records(manifest: dict[str, Any]) -> list[dict[str, Any]]: | |
| records: dict[str, dict[str, Any]] = {} | |
| for case in manifest["cases"]: | |
| scene = case["scene"] | |
| if scene in records: | |
| continue | |
| base = deepcopy(case) | |
| base["case_id"] = scene | |
| base["traj"] = None | |
| base["target_path"] = None | |
| base["camera_control"] = None | |
| base["pair_id"] = None | |
| metadata = deepcopy(base.get("metadata", {})) | |
| metadata.pop("camera_control_provenance", None) | |
| base["metadata"] = metadata | |
| records[scene] = base | |
| return [records[key] for key in sorted(records)] | |
| def control_document(source: dict[str, Any], relative: np.ndarray) -> dict[str, Any]: | |
| frames = source["frames"] | |
| num_frames = len(frames) | |
| if len(relative) != num_frames: | |
| raise ValueError("source and relative trajectory lengths differ") | |
| source_c2w = np.asarray([frame["c2w"] for frame in frames], dtype=np.float64) | |
| target_c2w = source_c2w @ relative | |
| return { | |
| "format_version": source["format_version"], | |
| "camera_model": source["camera_model"], | |
| "pose_type": source["pose_type"], | |
| "coordinate_system": source["coordinate_system"], | |
| "image_hw": source["image_hw"], | |
| "num_frames": num_frames, | |
| "frames": [ | |
| { | |
| "frame_index": index, | |
| "c2w": target_c2w[index].tolist(), | |
| "intrinsics": deepcopy(frames[index]["intrinsics"]), | |
| } | |
| for index in range(num_frames) | |
| ], | |
| } | |
| def controlled_case(base: dict[str, Any], name: str, params: dict[str, float]) -> dict[str, Any]: | |
| scene = base["scene"] | |
| case = deepcopy(base) | |
| case["case_id"] = f"{scene}__{name}" | |
| case["traj"] = name | |
| case["target_path"] = None | |
| case["camera_control"] = { | |
| "path": f"camera_controls/{scene}/{name}/transforms.json", | |
| "variant": "default", | |
| } | |
| case["pair_id"] = None | |
| case["metadata"]["camera_control_provenance"] = { | |
| "source": PROVENANCE, | |
| "spec_path": f"trajectory_specs/{name}.json", | |
| "mode": "relative", | |
| "composition": COMPOSITION, | |
| "num_frames": base["num_frames"], | |
| "angle_degrees": params.get("angle"), | |
| "distance": params.get("distance"), | |
| "distance_unit": "source_reconstruction_unit" if "distance" in params else None, | |
| "orbit_radius": params.get("orbit_radius"), | |
| "orbit_radius_unit": "source_reconstruction_unit" if "orbit_radius" in params else None, | |
| } | |
| return case | |
| def update_manifest(manifest: dict[str, Any], bases: list[dict[str, Any]]) -> dict[str, Any]: | |
| output = deepcopy(manifest) | |
| cases = [ | |
| controlled_case(base, name, params) | |
| for base in bases | |
| for name, params in CONTROL_SPECS.items() | |
| ] | |
| total_source_frames = sum(base["num_frames"] for base in bases) | |
| output["protocol"]["control"] = "camera" | |
| output["camera"].update({ | |
| "default_control_variant": "default", | |
| "synthetic_control_mode": "relative", | |
| "synthetic_control_composition": COMPOSITION, | |
| }) | |
| output["extensions"]["camera_trajectory_specs"] = { | |
| "path": "trajectory_specs/<trajectory_id>.json", | |
| "meaning": "NeoVerse predefined relative endpoint template sampled to each source length", | |
| "source": PROVENANCE, | |
| } | |
| output["statistics"] = { | |
| "num_scenes": len(bases), | |
| "num_cases": len(cases), | |
| "num_source_frames": total_source_frames, | |
| "num_camera_control_cases": len(cases), | |
| "num_camera_control_frames": total_source_frames * len(CONTROL_SPECS), | |
| "camera_control_trajectory_distribution": { | |
| name: len(bases) for name in CONTROL_SPECS | |
| }, | |
| "num_pairs": 0, | |
| "num_unpaired_cases": len(cases), | |
| } | |
| output["pairing"].update({ | |
| "scene_identity": "Each DynPose source scene is paired only with synthetic camera controls, not target RGB.", | |
| "temporal_alignment": "control frame index matches the observed source frame index", | |
| "pairs": [], | |
| "unpaired_sources": [ | |
| { | |
| "case_id": case["case_id"], | |
| "source_scene_id": case["scene"], | |
| "source_path": case["source_path"], | |
| "num_frames": case["num_frames"], | |
| "reason": "synthetic_camera_control_only_no_target_rgb", | |
| } | |
| for case in cases | |
| ], | |
| }) | |
| output["cases"] = cases | |
| return output | |
| def validate(root: Path) -> dict[str, Any]: | |
| manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8")) | |
| errors: list[str] = [] | |
| max_first_error = 0.0 | |
| max_composition_error = 0.0 | |
| max_orthonormal_error = 0.0 | |
| max_determinant_error = 0.0 | |
| relative_cache: dict[tuple[str, int], np.ndarray] = {} | |
| case_ids = [case["case_id"] for case in manifest["cases"]] | |
| control_paths = [case["camera_control"]["path"] for case in manifest["cases"]] | |
| if len(case_ids) != len(set(case_ids)): | |
| errors.append("duplicate case_id") | |
| if len(control_paths) != len(set(control_paths)): | |
| errors.append("duplicate camera control path") | |
| for case in manifest["cases"]: | |
| control_path = root / case["camera_control"]["path"] | |
| source_path = root / case["source_path"] / "transforms.json" | |
| if not control_path.is_file(): | |
| errors.append(f"missing {control_path.relative_to(root)}") | |
| continue | |
| control = json.loads(control_path.read_text(encoding="utf-8")) | |
| source = json.loads(source_path.read_text(encoding="utf-8")) | |
| num_frames = case["num_frames"] | |
| if len(control["frames"]) != num_frames or len(source["frames"]) != num_frames: | |
| errors.append(f"{case['case_id']}: wrong frame count") | |
| continue | |
| key = (case["traj"], num_frames) | |
| if key not in relative_cache: | |
| relative_cache[key] = relative_trajectory( | |
| case["traj"], CONTROL_SPECS[case["traj"]], num_frames | |
| ) | |
| relative = relative_cache[key] | |
| control_c2w = np.asarray([frame["c2w"] for frame in control["frames"]]) | |
| source_c2w = np.asarray([frame["c2w"] for frame in source["frames"]]) | |
| max_first_error = max(max_first_error, float(np.max(np.abs(control_c2w[0] - source_c2w[0])))) | |
| expected_c2w = source_c2w @ relative | |
| max_composition_error = max( | |
| max_composition_error, float(np.max(np.abs(control_c2w - expected_c2w))) | |
| ) | |
| rotations = control_c2w[:, :3, :3] | |
| max_orthonormal_error = max( | |
| max_orthonormal_error, | |
| float(np.max(np.abs(rotations @ np.swapaxes(rotations, 1, 2) - np.eye(3)[None]))), | |
| ) | |
| max_determinant_error = max( | |
| max_determinant_error, | |
| float(np.max(np.abs(np.linalg.det(rotations) - 1.0))), | |
| ) | |
| if not np.isfinite(control_c2w).all(): | |
| errors.append(f"{case['case_id']}: non-finite pose") | |
| if [frame["frame_index"] for frame in control["frames"]] != list(range(num_frames)): | |
| errors.append(f"{case['case_id']}: invalid frame indexes") | |
| if [frame["intrinsics"] for frame in control["frames"]] != [ | |
| frame["intrinsics"] for frame in source["frames"] | |
| ]: | |
| errors.append(f"{case['case_id']}: intrinsics differ from source") | |
| statistics = manifest.get("statistics", {}) | |
| if len(manifest["cases"]) != len(CONTROL_SPECS) * statistics.get("num_scenes", 0): | |
| errors.append("manifest case count does not match scene × trajectory count") | |
| if max_first_error > 1e-9: | |
| errors.append(f"first-frame mismatch: {max_first_error}") | |
| if max_composition_error > 1e-9: | |
| errors.append(f"composition mismatch: {max_composition_error}") | |
| if max_orthonormal_error > 1e-6: | |
| errors.append(f"rotation orthonormal error: {max_orthonormal_error}") | |
| if max_determinant_error > 1e-6: | |
| errors.append(f"rotation determinant error: {max_determinant_error}") | |
| if errors: | |
| raise RuntimeError("\n".join(errors[:20])) | |
| return { | |
| "scenes": statistics["num_scenes"], | |
| "cases": len(manifest["cases"]), | |
| "trajectories": list(CONTROL_SPECS), | |
| "camera_control_frames": statistics["num_camera_control_frames"], | |
| "min_frames": min(case["num_frames"] for case in manifest["cases"]), | |
| "max_frames": max(case["num_frames"] for case in manifest["cases"]), | |
| "max_first_frame_pose_error": max_first_error, | |
| "max_composition_error": max_composition_error, | |
| "max_rotation_orthonormal_error": max_orthonormal_error, | |
| "max_rotation_determinant_error": max_determinant_error, | |
| } | |
| def build(root: Path) -> dict[str, Any]: | |
| manifest_path = root / "manifest.json" | |
| manifest = json.loads(manifest_path.read_text(encoding="utf-8")) | |
| bases = source_records(manifest) | |
| if len(bases) != 377: | |
| raise ValueError(f"expected 377 DynPose scenes, found {len(bases)}") | |
| spec_root = root / "trajectory_specs" | |
| spec_root.mkdir(parents=True, exist_ok=True) | |
| for name, params in CONTROL_SPECS.items(): | |
| (spec_root / f"{name}.json").write_text( | |
| json.dumps(trajectory_template(name, params), indent=2) + "\n", | |
| encoding="utf-8", | |
| ) | |
| relative_cache: dict[tuple[str, int], np.ndarray] = {} | |
| for base in bases: | |
| scene = base["scene"] | |
| source_path = root / base["source_path"] / "transforms.json" | |
| source = json.loads(source_path.read_text(encoding="utf-8")) | |
| num_frames = len(source["frames"]) | |
| if num_frames != base["num_frames"]: | |
| raise ValueError(f"{scene}: manifest/source frame count mismatch") | |
| for name, params in CONTROL_SPECS.items(): | |
| key = (name, num_frames) | |
| if key not in relative_cache: | |
| relative_cache[key] = relative_trajectory(name, params, num_frames) | |
| relative = relative_cache[key] | |
| output_path = root / "camera_controls" / scene / name / "transforms.json" | |
| output_path.parent.mkdir(parents=True, exist_ok=True) | |
| output_path.write_text( | |
| json.dumps(control_document(source, relative), indent=2) + "\n", | |
| encoding="utf-8", | |
| ) | |
| manifest_temp = manifest_path.with_suffix(".json.tmp") | |
| manifest_temp.write_text( | |
| json.dumps(update_manifest(manifest, bases), indent=2, ensure_ascii=False) + "\n", | |
| encoding="utf-8", | |
| ) | |
| manifest_temp.replace(manifest_path) | |
| return validate(root) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--root", type=Path, default=ROOT) | |
| parser.add_argument("--check", action="store_true") | |
| args = parser.parse_args() | |
| result = validate(args.root) if args.check else build(args.root) | |
| print(json.dumps(result, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |