Spaces:
Running on Zero

File size: 21,063 Bytes
7547a6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
"""Two panels for one tracked clip: the input frames and the 3D trajectories over the depth cloud."""
from pathlib import Path
from typing import Optional

import cv2
import imageio
import matplotlib.pyplot as plt
import numpy as np

DEPTH_EDGE_RTOL = 0.05
SKYSEG_INPUT_SIZE = (320, 320)
SKYSEG_NON_SKY_THRESHOLD = 0.875
SKYSEG_URL = "https://huggingface.co/JianyuanWang/skyseg/resolve/main/skyseg.onnx"
_SKYSEG_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
_SKYSEG_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)


def move_cameras_backwards(c2ws, distance=0.5, lift_height=0.0, tilt_down_deg=0.0):
    """Push cameras back along the optical axis, lift, and tilt down."""
    new_c2ws = c2ws.copy()
    theta = np.radians(tilt_down_deg)
    R_tilt = np.array([
        [1, 0, 0],
        [0, np.cos(theta), -np.sin(theta)],
        [0, np.sin(theta), np.cos(theta)],
    ])
    for i in range(len(new_c2ws)):
        forward_vector = new_c2ws[i, :3, 2]
        new_c2ws[i, :3, 3] -= distance * forward_vector
        new_c2ws[i, 1, 3] -= lift_height
        new_c2ws[i, :3, :3] = new_c2ws[i, :3, :3] @ R_tilt
    return new_c2ws


def ensure_4x4(c2w):
    """Convert (3, 4) or (T, 3, 4) camera poses to homogeneous 4x4 form."""
    if c2w.ndim == 2 and c2w.shape == (3, 4):
        row = np.array([[0, 0, 0, 1]], dtype=c2w.dtype)
        return np.concatenate([c2w, row], axis=0)
    if c2w.ndim == 3 and c2w.shape[1:] == (3, 4):
        row = np.tile(np.array([0, 0, 0, 1], dtype=c2w.dtype), (c2w.shape[0], 1, 1))
        return np.concatenate([c2w, row], axis=1)
    return c2w


def _as_uint8_rgb(image):
    """Convert an RGB float/uint8 image to contiguous uint8."""
    if image.dtype == np.uint8:
        return np.ascontiguousarray(image)
    return np.ascontiguousarray(
        np.clip(image * 255.0, 0, 255).astype(np.uint8)
    )


def scale_intrinsics_cv2(intrinsics: np.ndarray, src_hw, dst_hw) -> np.ndarray:
    """Intrinsics after cv2.INTER_LINEAR, from the resized grid src (H, W) onto dst (H, W).

    cv2.resize samples resized pixel u from dst coordinate (u + 0.5) * dst/src - 0.5, so
    fx' = fx * dst_w / src_w and cx' = (cx + 0.5) * dst_w / src_w - 0.5. The two axes scale separately.
    """
    src_h, src_w = src_hw
    dst_h, dst_w = dst_hw
    scaled = np.array(intrinsics, dtype=np.float64, copy=True)
    scale_x = dst_w / src_w
    scale_y = dst_h / src_h
    scaled[..., 0, 0] *= scale_x
    scaled[..., 1, 1] *= scale_y
    scaled[..., 0, 2] = (scaled[..., 0, 2] + 0.5) * scale_x - 0.5
    scaled[..., 1, 2] = (scaled[..., 1, 2] + 0.5) * scale_y - 0.5
    return scaled.astype(np.result_type(intrinsics, np.float32), copy=False)


def _render_point_cloud(points, colors, c2w, intrinsics, render_hw, point_size):
    """Project one world-space point map onto a white RGB canvas."""
    render_h, render_w = render_hw
    frame = np.full((render_h, render_w, 3), 255, dtype=np.uint8)
    points = np.asarray(points).reshape(-1, 3)
    colors = _as_uint8_rgb(np.asarray(colors)).reshape(-1, 3)

    finite = np.isfinite(points).all(axis=1)
    if not np.any(finite):
        return frame
    points, colors = points[finite], colors[finite]

    w2c = np.linalg.inv(c2w)
    points_camera = (w2c[:3, :3] @ points.T).T + w2c[:3, 3]
    depth = points_camera[:, 2]
    valid_depth = depth > 0.001
    if not np.any(valid_depth):
        return frame

    points_camera = points_camera[valid_depth]
    colors = colors[valid_depth]
    depth = depth[valid_depth]
    projected = (intrinsics @ points_camera.T).T
    u = np.round(projected[:, 0] / (projected[:, 2] + 1e-8)).astype(int)
    v = np.round(projected[:, 1] / (projected[:, 2] + 1e-8)).astype(int)
    in_bounds = (u >= 0) & (u < render_w) & (v >= 0) & (v < render_h)
    if not np.any(in_bounds):
        return frame

    u, v = u[in_bounds], v[in_bounds]
    colors, depth = colors[in_bounds], depth[in_bounds]
    # Paint far-to-near so nearer points win when projections overlap.
    order = np.argsort(-depth)
    u, v, colors = u[order], v[order], colors[order]
    point_size = max(1, int(point_size))
    offset = -(point_size // 2)
    for dy in range(offset, offset + point_size):
        for dx in range(offset, offset + point_size):
            vv = np.clip(v + dy, 0, render_h - 1)
            uu = np.clip(u + dx, 0, render_w - 1)
            frame[vv, uu] = colors
    return frame


def _trail_start(frame_idx: int, trail_length: int) -> int:
    """Return the first frame of a trail that lives ``trail_length`` frames."""
    if trail_length < 0:
        return 0
    return max(0, frame_idx - trail_length + 1)


def _render_trajectories(
    sampled_trajectories,
    c2w,
    intrinsics,
    render_hw,
    frame_index,
    trajectory_length,
    trajectory_alpha,
    trajectory_width,
    background=None,
    z_near=0.3,
    visible=None,
):
    """Render trajectories ending at frame_index over an optional point cloud.

    visible (N, T) bool, when given, hides a point whose tracker logit is not positive. A trail segment is drawn
    only when both ends are visible.
    """
    render_h, render_w = render_hw
    if background is None:
        frame = np.full((render_h, render_w, 3), 255, dtype=np.uint8)
    else:
        frame = _as_uint8_rgb(background).copy()
        if frame.shape != (render_h, render_w, 3):
            raise ValueError("Trajectory background must match render_hw")
    if not len(sampled_trajectories):
        return frame

    cmap = plt.get_cmap("hsv")
    colors = [
        tuple(int(channel * 255) for channel in cmap(i / len(sampled_trajectories))[:3])
        for i in range(len(sampled_trajectories))
    ]
    start = _trail_start(frame_index, trajectory_length)
    tracks = sampled_trajectories[:, start:frame_index + 1]
    shown = None if visible is None else visible[:, start:frame_index + 1]
    w2c = np.linalg.inv(c2w)
    overlay = np.zeros((render_h, render_w, 4), dtype=np.uint8)
    width = max(1, int(trajectory_width))

    for index, (track, color) in enumerate(zip(tracks, colors)):
        camera_track = (w2c[:3, :3] @ track.T).T + w2c[:3, 3]
        finite = np.isfinite(camera_track).all(axis=1)
        projected = (intrinsics @ np.nan_to_num(camera_track).T).T
        points_2d = np.round(
            projected[:, :2] / (projected[:, 2:3] + 1e-8)
        ).astype(np.int32)
        valid = finite & (camera_track[:, 2] > z_near)
        if shown is not None:
            valid = valid & shown[index]
        segment_count = max(1, len(track) - 1)
        for segment in range(len(track) - 1):
            if not (valid[segment] and valid[segment + 1]):
                continue
            alpha = int(
                255
                * trajectory_alpha
                * (0.5 + 0.5 * (segment + 1) / segment_count)
            )
            cv2.line(
                overlay,
                tuple(points_2d[segment]),
                tuple(points_2d[segment + 1]),
                (*color, alpha),
                width,
                cv2.LINE_AA,
            )
        if valid[-1]:
            cv2.circle(
                overlay,
                tuple(points_2d[-1]),
                width,
                (*color, int(255 * trajectory_alpha)),
                -1,
            )

    alpha = overlay[:, :, 3:] / 255.0
    return (overlay[:, :, :3] * alpha + frame * (1 - alpha)).astype(np.uint8)


def points_inside_image(trajectories, c2ws, intrinsics, image_hw):
    """(N, T) bool: each world point projects inside that frame's real camera image.

    ``c2ws`` are the unmoved cameras. A point counts only when it is in front of that camera and its
    pixel lies in ``[0, W) x [0, H)`` of ``image_hw``.
    """
    trajectories = np.asarray(trajectories, dtype=np.float64)
    count, frames, _ = trajectories.shape
    del count
    c2ws = ensure_4x4(np.asarray(c2ws, dtype=np.float64))[:frames]
    intrinsics = np.asarray(intrinsics, dtype=np.float64)[:frames]
    if c2ws.shape[0] != frames or intrinsics.shape != (frames, 3, 3):
        raise ValueError(
            f"c2ws and intrinsics must cover {frames} frames, got {c2ws.shape} and {intrinsics.shape}"
        )
    w2c = np.linalg.inv(c2ws)
    camera = np.einsum("tij,ntj->nti", w2c[:, :3, :3], trajectories) + w2c[None, :, :3, 3]
    projected = np.einsum("tij,ntj->nti", intrinsics, np.nan_to_num(camera))
    pixels = projected[..., :2] / (projected[..., 2:3] + 1e-8)
    height, width = image_hw
    return (
        np.isfinite(camera).all(axis=-1)
        & (camera[..., 2] > 0)
        & (pixels[..., 0] >= 0) & (pixels[..., 0] < width)
        & (pixels[..., 1] >= 0) & (pixels[..., 1] < height)
    )


def unproject_depth(depth: np.ndarray, intrinsics: np.ndarray, c2w: np.ndarray) -> np.ndarray:
    """(H, W) depth -> (H, W, 3) world points; pixels without depth become NaN."""
    H, W = depth.shape
    v, u = np.meshgrid(np.arange(H, dtype=np.float32), np.arange(W, dtype=np.float32), indexing="ij")
    pixels = np.stack([u, v, np.ones_like(u)], axis=-1)
    local = (pixels @ np.linalg.inv(intrinsics).T) * depth[..., None]
    world = local @ c2w[:3, :3].T + c2w[:3, 3]
    world[depth <= 0] = np.nan
    return world


def _depth_edge_mask(depth: np.ndarray, rtol: float = DEPTH_EDGE_RTOL) -> np.ndarray:
    """True where the 3x3 relative depth spread exceeds ``rtol``.

    Invalid pixels (non-finite or <= 0) stay out of the neighborhood extrema, so the
    valid/invalid boundary is not treated as a depth edge.
    """
    depth = np.asarray(depth, dtype=np.float32)
    valid = np.isfinite(depth) & (depth > 0)
    if not np.any(valid):
        return np.zeros(depth.shape, dtype=bool)
    kernel = np.ones((3, 3), np.uint8)
    # dilate = max: invalid as 0 so they never raise the max among positive depths
    d_max = cv2.dilate(np.where(valid, depth, 0.0).astype(np.float32), kernel)
    # erode = min: invalid as a large value so they never lower the min
    d_min = cv2.erode(np.where(valid, depth, np.float32(1e9)).astype(np.float32), kernel)
    relative = np.zeros_like(depth, dtype=np.float32)
    np.divide(d_max - d_min, depth, out=relative, where=valid)
    return valid & (relative > rtol)


def filter_depth_outliers(depth: np.ndarray, rtol: float = DEPTH_EDGE_RTOL) -> np.ndarray:
    """Copy of ``depth`` with depth-discontinuity pixels set to 0 (not drawn)."""
    out = np.array(depth, dtype=np.float32, copy=True)
    out[_depth_edge_mask(out, rtol)] = 0
    return out


def _skyseg_model_path() -> Path:
    return Path(__file__).resolve().parents[1] / "checkpoints" / "skyseg.onnx"


def _ensure_skyseg_model(path: Path) -> Path:
    if path.is_file():
        return path
    path.parent.mkdir(parents=True, exist_ok=True)
    import urllib.request
    print(f"downloading skyseg to {path}", flush=True)
    tmp = path.with_suffix(path.suffix + ".partial")
    try:
        urllib.request.urlretrieve(SKYSEG_URL, tmp)
        tmp.replace(path)
    except Exception:
        tmp.unlink(missing_ok=True)
        raise
    return path


class _SkySegmenter:
    """skyseg.onnx session. Higher raw scores are sky; ``non_sky`` is 1 minus the normalized score."""

    def __init__(self, model_path: Optional[Path] = None):
        import onnxruntime as ort
        model = _ensure_skyseg_model(Path(model_path) if model_path is not None else _skyseg_model_path())
        self.session = ort.InferenceSession(str(model), providers=["CPUExecutionProvider"])
        self.input_name = self.session.get_inputs()[0].name
        self.output_name = self.session.get_outputs()[0].name

    def non_sky(self, image: np.ndarray, hw) -> np.ndarray:
        """Non-sky confidence in [0, 1] at ``hw`` = (H, W)."""
        rgb = _as_uint8_rgb(image)
        bgr = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
        resized = cv2.resize(bgr, SKYSEG_INPUT_SIZE)
        x = cv2.cvtColor(resized, cv2.COLOR_BGR2RGB).astype(np.float32)
        x = (x / 255.0 - _SKYSEG_MEAN) / _SKYSEG_STD
        x = np.ascontiguousarray(x.transpose(2, 0, 1)[None])
        result = np.asarray(self.session.run([self.output_name], {self.input_name: x})).squeeze()
        low, high = float(result.min()), float(result.max())
        result = (result - low) / max(high - low, 1e-8)
        height, width = hw
        result = cv2.resize(result.astype(np.float32), (width, height), interpolation=cv2.INTER_LINEAR)
        return 1.0 - result


def filter_sky_depth(depth: np.ndarray, image: np.ndarray, segmenter: _SkySegmenter) -> np.ndarray:
    """Copy of ``depth`` with sky pixels (non-sky confidence <= 0.875) set to 0."""
    out = np.array(depth, dtype=np.float32, copy=True)
    non_sky = segmenter.non_sky(image, out.shape[:2])
    out[non_sky <= SKYSEG_NON_SKY_THRESHOLD] = 0
    return out


def _camera_cone_world(depth, intrinsics, c2w, cone_size):
    """Apex plus the four image corners at ``cone_size`` times the median valid depth, in world space.

    Returns (5, 3) with the camera center first, or None when the frame has no positive depth.
    ``cone_size`` scales the pyramid along the field of view. The field of view itself stays the same.
    """
    valid = depth[np.isfinite(depth) & (depth > 0)]
    if valid.size == 0:
        return None
    height, width = depth.shape
    corners = np.array([
        [0, 0, 1],
        [width - 1, 0, 1],
        [width - 1, height - 1, 1],
        [0, height - 1, 1],
    ], dtype=np.float64)
    local = (corners @ np.linalg.inv(np.asarray(intrinsics, dtype=np.float64)).T) * (float(np.median(valid)) * cone_size)
    pose = ensure_4x4(np.asarray(c2w, dtype=np.float64))
    base = local @ pose[:3, :3].T + pose[:3, 3]
    return np.concatenate([pose[:3, 3][None], base], axis=0)


def _draw_camera_cone(image, cone_world, render_c2w, render_k, z_near, width):
    """Draw a black pyramid on a copy of image. A segment is skipped when either end is not in front of the view."""
    frame = _as_uint8_rgb(image).copy()
    w2c = np.linalg.inv(render_c2w)
    camera = (w2c[:3, :3] @ cone_world.T).T + w2c[:3, 3]
    finite = np.isfinite(camera).all(axis=1)
    projected = (render_k @ np.nan_to_num(camera).T).T
    points_2d = np.round(projected[:, :2] / (projected[:, 2:3] + 1e-8)).astype(np.int32)
    valid = finite & (camera[:, 2] > z_near)
    edges = ((0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (2, 3), (3, 4), (4, 1))
    width = max(1, int(width))
    for start, end in edges:
        if not (valid[start] and valid[end]):
            continue
        cv2.line(frame, tuple(points_2d[start]), tuple(points_2d[end]), (0, 0, 0), width, cv2.LINE_AA)
    return frame


def render_panels(
    images: np.ndarray,
    depths: np.ndarray,
    intrinsics: np.ndarray,
    c2ws: np.ndarray,
    trajectories: np.ndarray,
    output_path: Path,
    view_images: np.ndarray,
    view_intrinsics: np.ndarray,
    fps: int = 15,
    point_size: int = 2,
    trajectory_length: int = 0,
    trajectory_alpha: float = 1.0,
    trajectory_width: int = 2,
    distance: float = 0.1,
    lift_height: float = 0.05,
    tilt_down_deg: float = -6,
    z_near: float = 0.3,
    cone_size: float = 0.1,
    filter_sky: bool = False,
) -> Path:
    """Write the input panel and the trajectory panel side by side as an MP4.

    images: (T, H, W, 3) in [0, 1]; depths: (T, H, W); intrinsics: (T, 3, 3); c2ws: (T, 4, 4);
    trajectories: (N, T, 3) world-space tracks of the query points.
    view_images (T, H0, W0, 3) and view_intrinsics (T, 3, 3) are the display frames and the cameras that match
    them. The point cloud is still unprojected from images, depths and intrinsics, so those three stay at the
    inference resolution. The viewing camera follows each frame's camera, moved back by distance, lift_height
    and tilt_down_deg.
    The current frame's real camera is drawn as a black pyramid. cone_size is the base depth as a fraction of that
    frame's median valid depth, so a smaller value shrinks the pyramid without changing its field of view.
    Depth-discontinuity pixels are dropped from the point cloud only; camera cone and tracks stay unchanged.
    filter_sky drops sky pixels from that same cloud, before the edge filter. Camera cone and tracks stay unchanged.
    Points that project outside that frame's real camera image are hidden. The point cloud and camera cone ignore that.
    """
    if cone_size <= 0:
        raise ValueError(f"cone_size must be > 0, got {cone_size}")
    if view_images.shape[0] != images.shape[0] or view_images.ndim != 4 or view_images.shape[-1] != 3:
        raise ValueError("view_images must be (T, H, W, 3) with the same frame count as images")
    if tuple(depths.shape[:3]) != tuple(images.shape[:3]):
        raise ValueError("depths must match images")
    if view_intrinsics.shape != (view_images.shape[0], 3, 3):
        raise ValueError("view_intrinsics must be (T, 3, 3) matching view_images")
    visible = points_inside_image(trajectories, c2ws, intrinsics, images.shape[1:3])
    frame_count, source_h, source_w = view_images.shape[:3]
    c2ws = ensure_4x4(np.asarray(c2ws))
    render_hw = (source_h, source_w)
    render_c2ws = move_cameras_backwards(c2ws[:frame_count], distance=distance, lift_height=lift_height, tilt_down_deg=tilt_down_deg)
    trail_length = frame_count if trajectory_length <= 0 else trajectory_length
    order = np.argsort(trajectories[:, 0, 1])
    trajectories = trajectories[order]
    visible = visible[order]

    output_path = Path(output_path)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    sky_segmenter = _SkySegmenter() if filter_sky else None
    writer = imageio.get_writer(str(output_path), fps=fps, codec="libx264", pixelformat="yuv420p", macro_block_size=1)
    try:
        for frame_index in range(frame_count):
            render_c2w = render_c2ws[frame_index]
            render_K = view_intrinsics[frame_index]
            depth_for_cloud = depths[frame_index]
            if sky_segmenter is not None:
                depth_for_cloud = filter_sky_depth(depth_for_cloud, images[frame_index], sky_segmenter)
            depth_for_cloud = filter_depth_outliers(depth_for_cloud)
            points = unproject_depth(depth_for_cloud, intrinsics[frame_index], c2ws[frame_index])
            cloud_panel = _render_point_cloud(
                points, _as_uint8_rgb(images[frame_index]), render_c2w, render_K, render_hw, point_size
            )
            cone_world = _camera_cone_world(depths[frame_index], intrinsics[frame_index], c2ws[frame_index], cone_size)
            input_panel = cv2.resize(
                _as_uint8_rgb(view_images[frame_index]), (render_hw[1], render_hw[0]), interpolation=cv2.INTER_LINEAR
            )
            traj_panel = _render_trajectories(
                trajectories, render_c2w, render_K, render_hw, frame_index, trail_length,
                trajectory_alpha, trajectory_width, background=cloud_panel, z_near=z_near, visible=visible,
            )
            if cone_world is not None:
                traj_panel = _draw_camera_cone(
                    traj_panel, cone_world, render_c2w, render_K, z_near, trajectory_width,
                )
            writer.append_data(np.concatenate([input_panel, traj_panel], axis=1))
    finally:
        writer.close()
    return output_path


def sample_mask_queries(mask_path: str, depth: np.ndarray, intrinsics: np.ndarray, extrinsics: np.ndarray, num_points: int, seed: int, mask_margin: int = 0) -> np.ndarray:
    """Sample num_points pixels from the non-zero part of mask_path that have depth, and lift them to frame-0
    world-space query points (N, 4) = (frame, x, y, z).

    mask_margin is a pixel count at the depth resolution. The mask is eroded by that many pixels before sampling,
    so points closer than this to the mask boundary are left out. 0 keeps every valid mask pixel.
    """
    mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)
    if mask is None:
        raise FileNotFoundError(f"Cannot read the query mask {mask_path}")
    margin = int(mask_margin)
    if margin < 0:
        raise ValueError(f"mask_margin must be >= 0, got {margin}")
    H, W = depth.shape
    mask = cv2.resize((mask > 0).astype(np.uint8), (W, H), interpolation=cv2.INTER_NEAREST)
    if margin > 0:
        kernel = np.ones((3, 3), dtype=np.uint8)
        mask = cv2.erode(mask, kernel, iterations=margin)
    mask = mask.astype(bool)
    rows, cols = np.nonzero(mask & (depth > 0))
    if len(rows) == 0:
        raise ValueError(f"No pixel of {mask_path} has a valid depth after mask_margin={margin}")
    selected = np.random.default_rng(seed).choice(len(rows), size=min(num_points, len(rows)), replace=False)
    rows, cols = rows[selected], cols[selected]
    d = depth[rows, cols]
    pixels = np.stack([cols, rows, np.ones_like(cols)], axis=-1).astype(np.float64)
    local = (pixels @ np.linalg.inv(intrinsics).T) * d[:, None]
    c2w = np.linalg.inv(extrinsics)
    world = local @ c2w[:3, :3].T + c2w[:3, 3]
    return np.concatenate([np.zeros((len(world), 1)), world], axis=-1).astype(np.float32)