File size: 7,457 Bytes
9c890d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
"""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}