"""Export calibrated NPZ clips and SCALE4D results to viewer scene assets.""" from __future__ import annotations import gzip import json import subprocess from pathlib import Path import numpy as np from PIL import Image from demo.scale4d_view_count.bundle import bundle_path, validate_scene def write_atlas(rgbs: np.ndarray, path: Path, fps: int = 8) -> dict: views, frames, channels, height, width = rgbs.shape if not 1 <= views <= 10 or channels != 3 or rgbs.dtype != np.uint8: raise ValueError("Expected 1–10 uint8 RGB views") columns = min(5, views) rows = (views + columns - 1) // columns cell_width = 256 cell_height = round(cell_width * height / width) cell_height += cell_height % 2 if path.exists(): raise FileExistsError(path) command = [ "ffmpeg", "-n", "-loglevel", "error", "-f", "rawvideo", "-pixel_format", "rgb24", "-video_size", f"{cell_width * columns}x{cell_height * rows}", "-framerate", str(fps), "-i", "pipe:0", "-c:v", "libvpx-vp9", "-crf", "33", "-b:v", "0", "-pix_fmt", "yuv420p", str(path), ] process = subprocess.Popen(command, stdin=subprocess.PIPE) try: for frame in range(frames): atlas = Image.new("RGB", (cell_width * columns, cell_height * rows)) for camera in range(views): image = Image.fromarray(rgbs[camera, frame].transpose(1, 2, 0)) image = image.resize( (cell_width, cell_height), Image.Resampling.BILINEAR ) atlas.paste( image, ( (camera % columns) * cell_width, (camera // columns) * cell_height, ), ) process.stdin.write(atlas.tobytes()) finally: process.stdin.close() status = process.wait() if status: raise RuntimeError(f"ffmpeg failed with exit code {status}") return { "columns": columns, "rows": rows, "cell_width": cell_width, "cell_height": cell_height, } def track_layer(positions: np.ndarray, valid: np.ndarray) -> dict: return { "positions": np.nan_to_num( positions.astype(np.float64), nan=0, posinf=0, neginf=0 ) .round(5) .transpose(1, 0, 2) .tolist(), "valid": valid.T.tolist(), } def export_scene(root: Path, record: dict, scores: list[dict], output: Path) -> dict: dataset = record["id"] with np.load(bundle_path(root, record["input"]), allow_pickle=False) as data: rgbs = data["rgbs"] poses, intrinsics = data["cameras_to_world"], data["intrinsics"] uv, times = data["query_uv"], data["query_times"] with np.load(bundle_path(root, record["results"]), allow_pickle=False) as data: positions = data["uv_depth"] if not np.array_equal(data["views"], np.arange(1, 11)): raise ValueError("Expected result counts 1–10") with np.load(bundle_path(root, record["labels"]), allow_pickle=False) as data: gt, visible = data["gt_tracks_target_camera"], data["visibility"] frames, queries = gt.shape[:2] if ( positions.shape != (10, frames, queries, 3) or rgbs.shape[:2] != (10, frames) or len(uv) != queries ): raise ValueError("Clip inputs, predictions, and labels are not synchronized") valid = ( np.isfinite(positions).all(-1) & (positions[..., 2] > 0) & (np.abs(positions).max(-1) < 32) ) selected_scores = sorted( [row for row in scores if row["dataset"] == dataset], key=lambda row: int(row["views"]), ) if [int(row["views"]) for row in selected_scores] != list(range(1, 11)): raise ValueError("Expected a full score table for this scene") states = [] for index, row in enumerate(selected_scores): errors = np.linalg.norm(positions[index].astype(np.float64) - gt, axis=-1) states.append( { "views": index + 1, **track_layer(positions[index], valid[index]), "aj": float(row["aj"]), "apd": float(row["apd"]), "mean_error_cm": float(errors[visible].mean() * 100), } ) if record.get("context"): with np.load(bundle_path(root, record["context"]), allow_pickle=False) as data: context, context_valid, colors = ( data["positions"], data["valid"], data["colors"], ) for index, state in enumerate(states): state["dense"] = { **track_layer(context[index], context_valid[index]), "colors": colors.tolist(), } height, width = rgbs.shape[-2:] pixels = np.rint(uv).astype(int) pixels[:, 0] = pixels[:, 0].clip(0, width - 1) pixels[:, 1] = pixels[:, 1].clip(0, height - 1) colors = rgbs[0, times, :, pixels[:, 1], pixels[:, 0]] points = gt[visible] target = np.median(points, axis=0) extent = max(float(np.linalg.norm(points - target, axis=-1).max()), 0.06) scene = { "id": dataset, "dataset": dataset, "label": record.get("label", record["scene"]), "frames": frames, "fps": 8, "video": f"{dataset}.webm", "camera_ids": record["camera_ids"], "image_width": width, "image_height": height, "intrinsics": intrinsics.astype(np.float64).round(6).tolist(), "relative_cameras": (np.linalg.inv(poses) @ poses[0:1]) .astype(np.float64) .round(7) .tolist(), "fov": float(np.degrees(2 * np.arctan(height / (2 * intrinsics[0, 0, 1, 1])))), "target": target.tolist(), "extent": extent, "history": 4, "default_frame": min(30, frames - 1), "dyn": { "windows": [ { "start": 0, "own_end": frames, "end": frames, "L": frames, "n": queries, } ] }, "states": states, "gt": track_layer(gt, visible), "colors": colors.tolist(), "query_times": times.tolist(), "query_count": queries, "position_source": "uv_depth", "checkpoint_iteration": 140000, "selection": "Selected from the frozen 1–10-view sweep; full scored query set.", "benchmark_scores": [ { "views": int(row["views"]), "aj": float(row["aj"]), "apd": float(row["apd"]), } for row in selected_scores ], } validate_scene(scene) output.mkdir(parents=True, exist_ok=True) scene["video_grid"] = write_atlas(rgbs, output / scene["video"]) name = f"{dataset}.json.gz" with (output / name).open("xb") as handle: handle.write( gzip.compress( json.dumps(scene, separators=(",", ":"), allow_nan=False).encode(), compresslevel=6, mtime=0, ) ) return {"id": dataset, "dataset": dataset, "label": scene["label"], "data": name}