| """Convert ``mine_blender`` voxel exports into LiveWorld_comp input cases. |
| |
| Produces a depth-derived **static** background point cloud — what a depth sensor |
| would observe of the static scene. Mirroring SPMEM, we raycast the static voxel |
| cubes from ``--depth-views`` viewpoints sampled uniformly across the model's |
| generation range and union the first-hit surface points, then voxel-downsample |
| to dedupe the multi-view overlap. Dynamic (foreground) voxels are deliberately |
| kept out of ``pointcloud.npz`` (auto fg/bg split): the foreground is conditioned |
| separately via ``fg_projection.mp4`` / ``fg_mask_first.png``, and the background |
| point cloud is re-coloured per chunk at inference time. |
| |
| Per case output (matches ``LiveWorld_comp.core.inputs.load_user_inputs``): |
| |
| <name>/ |
| first_frame.png copied from ``input_image`` (resized to target_hw) |
| prompt.txt from ``prompt`` |
| geometry.npz keys: poses_c2w (N, 4, 4), K (3, 3), intrinsics_size |
| pointcloud.npz keys: points (M, 3) — STATIC background only |
| fg_mask_first.png from frame_0001 dyn voxels projected into pose 0 |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import sys |
| from dataclasses import dataclass |
| from pathlib import Path |
| from typing import Dict, List, Optional, Tuple |
|
|
| import cv2 |
| import numpy as np |
| from PIL import Image |
|
|
|
|
| TARGET_W_DEFAULT = 832 |
| TARGET_H_DEFAULT = 480 |
|
|
|
|
| |
| |
| |
|
|
| def compute_intrinsics_px(intr: dict, |
| target_w: int, |
| target_h: int) -> Tuple[float, float, float, float]: |
| """Convert Blender sensor intrinsics to pixel intrinsics at target_hw.""" |
| focal = float(intr["focal_length"]) |
| sw = float(intr["sensor_width"]) |
| sh = float(intr["sensor_height"]) |
| res_x = int(intr["resolution_x"]) |
| res_y = int(intr["resolution_y"]) |
| fit = intr.get("sensor_fit", "AUTO") |
|
|
| if fit == "VERTICAL": |
| fpx = focal / sh * res_y |
| elif fit == "HORIZONTAL": |
| fpx = focal / sw * res_x |
| else: |
| fpx = focal / sw * res_x if res_x >= res_y else focal / sh * res_y |
|
|
| fx = fpx * target_w / res_x |
| fy = fpx * target_h / res_y |
| cx = target_w / 2.0 |
| cy = target_h / 2.0 |
| return fx, fy, cx, cy |
|
|
|
|
| def blender_c2w_to_opencv_c2w(c2w_blender: np.ndarray) -> np.ndarray: |
| """Flip cam-local Y and Z columns to convert Blender → OpenCV camera frame.""" |
| c2w = c2w_blender.astype(np.float32).copy() |
| c2w[..., :3, 1:3] *= -1 |
| return c2w |
|
|
|
|
| def K_matrix(fx: float, fy: float, cx: float, cy: float) -> np.ndarray: |
| return np.array([[fx, 0.0, cx], |
| [0.0, fy, cy], |
| [0.0, 0.0, 1.0]], dtype=np.float32) |
|
|
|
|
| |
| |
| |
|
|
| _FACE_NORMALS = np.array([ |
| [-1, 0, 0], [+1, 0, 0], |
| [0, -1, 0], [0, +1, 0], |
| [0, 0, -1], [0, 0, +1], |
| ], dtype=np.float32) |
|
|
|
|
| def sample_cube_surface_points(centers: np.ndarray, |
| sizes: np.ndarray, |
| points_per_voxel: int, |
| rng: np.random.Generator, |
| return_normals: bool = False |
| ) -> Tuple[np.ndarray, np.ndarray]: |
| """Stratified per-face sampling on each voxel's surface. |
| |
| Returns |
| ------- |
| points : (N * K, 3) float32 — surface samples |
| normals : (N * K, 3) float32 — face normal per point (only if requested) |
| """ |
| N = len(centers) |
| if N == 0: |
| empty = np.zeros((0, 3), dtype=np.float32) |
| return empty, empty |
| K = int(points_per_voxel) |
| if K <= 0: |
| |
| pts = centers.astype(np.float32).copy() |
| nm = np.zeros_like(pts) |
| return pts, nm |
|
|
| per_face = max(1, (K + 5) // 6) |
| total_per_voxel = per_face * 6 |
|
|
| face_id = np.repeat(np.arange(6, dtype=np.int32), per_face) |
| face_axis = face_id // 2 |
| face_sign = ((face_id % 2) * 2 - 1).astype(np.float32) |
| uv = rng.uniform(-0.5, 0.5, size=(total_per_voxel, 2)).astype(np.float32) |
|
|
| unit_pts = np.zeros((total_per_voxel, 3), dtype=np.float32) |
| for f in range(6): |
| s, e = f * per_face, (f + 1) * per_face |
| axis = f // 2 |
| sign = float(face_sign[s]) |
| other_axes = [a for a in range(3) if a != axis] |
| unit_pts[s:e, axis] = sign * 0.5 |
| unit_pts[s:e, other_axes[0]] = uv[s:e, 0] |
| unit_pts[s:e, other_axes[1]] = uv[s:e, 1] |
|
|
| unit_normals = _FACE_NORMALS[face_id] |
|
|
| keep_slice = slice(None) |
| if total_per_voxel > K: |
| keep_idx = rng.choice(total_per_voxel, size=K, replace=False) |
| unit_pts = unit_pts[keep_idx] |
| unit_normals = unit_normals[keep_idx] |
| keep_slice = keep_idx |
|
|
| sizes_b = sizes.astype(np.float32).reshape(N, 1, 1) |
| pts = centers.astype(np.float32).reshape(N, 1, 3) + unit_pts.reshape(1, -1, 3) * sizes_b |
| pts = pts.reshape(-1, 3) |
|
|
| if return_normals: |
| nm = np.tile(unit_normals.reshape(1, -1, 3), (N, 1, 1)).reshape(-1, 3) |
| return pts, nm |
| return pts, np.zeros_like(pts) |
|
|
|
|
| |
| |
| |
|
|
| def cull_back_faces(points: np.ndarray, |
| normals: np.ndarray, |
| cam_positions: np.ndarray) -> np.ndarray: |
| """True if the point's face is front-facing toward AT LEAST one camera.""" |
| visible = np.zeros(len(points), dtype=bool) |
| for cam in cam_positions: |
| diff = cam[None] - points |
| dot = (normals * diff).sum(axis=1) |
| visible |= dot > 0.0 |
| return visible |
|
|
|
|
| def voxel_downsample_points(points: np.ndarray, voxel_size: float) -> np.ndarray: |
| if voxel_size <= 0 or len(points) == 0: |
| return points |
| keys = np.floor(points / voxel_size).astype(np.int64) |
| _, unique_idx = np.unique(keys, axis=0, return_index=True) |
| unique_idx.sort() |
| return points[unique_idx] |
|
|
|
|
| def voxel_downsample_with_colors(points: np.ndarray, |
| colors: np.ndarray, |
| voxel_size: float |
| ) -> Tuple[np.ndarray, np.ndarray]: |
| """Voxel-downsample ``points`` while keeping the matching color of the |
| representative sample. Returns ``(pts, cols)``.""" |
| if voxel_size <= 0 or len(points) == 0: |
| return points, colors |
| keys = np.floor(points / voxel_size).astype(np.int64) |
| _, unique_idx = np.unique(keys, axis=0, return_index=True) |
| unique_idx.sort() |
| return points[unique_idx], colors[unique_idx] |
|
|
|
|
| def build_unit_cube_surface_samples(K: int, seed: int = 0) -> np.ndarray: |
| """Return ``(K, 3) float32`` points uniformly distributed on the surface |
| of a unit cube centred at origin (so in ``[-0.5, 0.5]^3``). |
| |
| Used as a SHARED per-voxel template applied via:: |
| |
| world_pt = unit_sample * voxel_size + voxel_center |
| |
| By sharing one template across all voxels we get deterministic, time- |
| consistent per-voxel splats: each voxel's K samples follow the voxel |
| rigidly across frames, instead of re-randomising per-frame. |
| """ |
| rng = np.random.default_rng(seed) |
| per_face = max(1, (int(K) + 5) // 6) |
| total = per_face * 6 |
| face_id = np.repeat(np.arange(6, dtype=np.int32), per_face) |
| axis = face_id // 2 |
| side = ((face_id % 2) * 2 - 1).astype(np.float32) * 0.5 |
| uv = rng.uniform(-0.5, 0.5, size=(total, 2)).astype(np.float32) |
| samples = np.zeros((total, 3), dtype=np.float32) |
| for f in range(6): |
| s, e = f * per_face, (f + 1) * per_face |
| a = f // 2 |
| others = [aa for aa in range(3) if aa != a] |
| samples[s:e, a] = float(side[s]) |
| samples[s:e, others[0]] = uv[s:e, 0] |
| samples[s:e, others[1]] = uv[s:e, 1] |
| if total > K: |
| idx = rng.choice(total, size=int(K), replace=False) |
| samples = samples[idx] |
| return samples |
|
|
|
|
| def transform_unit_samples_per_voxel(unit_samples: np.ndarray, |
| centers: np.ndarray, |
| sizes: np.ndarray) -> np.ndarray: |
| """Apply ``(size_i, center_i)`` to a SHARED unit template per voxel. |
| Returns ``(N * K, 3)`` where rows ``[i*K:(i+1)*K)`` belong to voxel ``i``. |
| """ |
| N = len(centers) |
| if N == 0: |
| return np.zeros((0, 3), dtype=np.float32) |
| s = sizes.reshape(N, 1, 1).astype(np.float32) |
| c = centers.reshape(N, 1, 3).astype(np.float32) |
| u = unit_samples.reshape(1, -1, 3).astype(np.float32) |
| return (u * s + c).reshape(-1, 3) |
|
|
|
|
| |
| |
| |
|
|
| _CUBE_UNIT_VERTS = np.array([ |
| [-0.5, -0.5, -0.5], [+0.5, -0.5, -0.5], [+0.5, +0.5, -0.5], [-0.5, +0.5, -0.5], |
| [-0.5, -0.5, +0.5], [+0.5, -0.5, +0.5], [+0.5, +0.5, +0.5], [-0.5, +0.5, +0.5], |
| ], dtype=np.float32) |
|
|
| _CUBE_UNIT_FACES = np.array([ |
| [0, 2, 1], [0, 3, 2], |
| [4, 5, 6], [4, 6, 7], |
| [0, 1, 5], [0, 5, 4], |
| [3, 6, 2], [3, 7, 6], |
| [0, 7, 3], [0, 4, 7], |
| [1, 2, 6], [1, 6, 5], |
| ], dtype=np.int32) |
|
|
|
|
| def build_cube_triangle_mesh(centers: np.ndarray, |
| sizes: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: |
| """Build axis-aligned cube mesh: returns (verts (N*8, 3), faces (N*12, 3)).""" |
| N = len(centers) |
| if N == 0: |
| return (np.zeros((0, 3), np.float32), |
| np.zeros((0, 3), np.int32)) |
| sizes_b = sizes.astype(np.float32).reshape(N, 1, 1) |
| verts = (_CUBE_UNIT_VERTS[None] * sizes_b + |
| centers[:, None, :].astype(np.float32)).reshape(-1, 3) |
| offsets = (np.arange(N, dtype=np.int32) * 8).reshape(N, 1, 1) |
| faces = (_CUBE_UNIT_FACES[None] + offsets).reshape(-1, 3).astype(np.int32) |
| return verts.astype(np.float32), faces.astype(np.int32) |
|
|
|
|
| def _build_scene_for_frame(static_v: np.ndarray, static_f: np.ndarray, |
| dyn_c: np.ndarray, dyn_s: np.ndarray |
| ) -> Tuple[Optional[object], int, int]: |
| """Build an Open3D ``RaycastingScene`` for one frame with **separate** |
| geometry ids for static and dyn cubes. |
| |
| Returns ``(scene, static_id, dyn_id)`` where ``static_id`` / ``dyn_id`` are |
| Open3D geometry handles (or ``-1`` when that layer is empty). ``scene`` is |
| ``None`` if both layers are empty. |
| """ |
| import open3d as o3d |
| import open3d.core as o3c |
|
|
| dyn_v, dyn_f = build_cube_triangle_mesh(dyn_c, dyn_s) |
| if len(static_v) == 0 and len(dyn_v) == 0: |
| return None, -1, -1 |
|
|
| scene = o3d.t.geometry.RaycastingScene() |
| static_id = -1 |
| dyn_id = -1 |
| if len(static_v) > 0: |
| static_id = int(scene.add_triangles( |
| o3c.Tensor(static_v, dtype=o3c.float32), |
| o3c.Tensor(static_f.astype(np.uint32), dtype=o3c.uint32), |
| )) |
| if len(dyn_v) > 0: |
| dyn_id = int(scene.add_triangles( |
| o3c.Tensor(dyn_v, dtype=o3c.float32), |
| o3c.Tensor(dyn_f.astype(np.uint32), dtype=o3c.uint32), |
| )) |
| return scene, static_id, dyn_id |
|
|
|
|
| def raycast_static_at_camera0(static_centers: np.ndarray, |
| static_sizes: np.ndarray, |
| dyn_centers_at_0: np.ndarray, |
| dyn_sizes_at_0: np.ndarray, |
| pose_c2w_0: np.ndarray, |
| K: np.ndarray, |
| H: int, W: int, |
| max_depth: float = 200.0 |
| ) -> np.ndarray: |
| """Depth-derived static PC visible from **camera 0 only**. |
| |
| Why frame 0 only: with the current coloring strategy (only points whose |
| projection to ``first_frame.png`` is in-view AND outside ``fg_mask`` |
| get a color), any static surface visible only from later frames CANNOT |
| be coloured and will be dropped downstream. Casting rays for frames |
| 1..N-1 produces hits that are guaranteed to be discarded — pure waste. |
| |
| Includes ``dyn[0]`` as occluder so dyn-occluded static doesn't leak in. |
| Hits are un-deduped; caller voxel-downsamples. |
| """ |
| import open3d.core as o3c |
|
|
| static_v, static_f = build_cube_triangle_mesh(static_centers, static_sizes) |
| scene, static_id, _ = _build_scene_for_frame( |
| static_v, static_f, dyn_centers_at_0, dyn_sizes_at_0 |
| ) |
| if scene is None or static_id < 0: |
| return np.zeros((0, 3), dtype=np.float32) |
|
|
| intrinsic = o3c.Tensor(K.astype(np.float64), dtype=o3c.float64) |
| w2c = np.linalg.inv(pose_c2w_0).astype(np.float64) |
| rays = scene.create_rays_pinhole( |
| intrinsic_matrix=intrinsic, |
| extrinsic_matrix=o3c.Tensor(w2c, dtype=o3c.float64), |
| width_px=W, height_px=H, |
| ) |
| ans = scene.cast_rays(rays) |
| t_hit = ans["t_hit"].numpy() |
| geom_ids = ans["geometry_ids"].numpy() |
| valid = np.isfinite(t_hit) & (t_hit > 1e-3) & (t_hit < max_depth) |
| sm = valid & (geom_ids == static_id) |
| if not sm.any(): |
| return np.zeros((0, 3), dtype=np.float32) |
|
|
| rays_np = rays.numpy() |
| hits = rays_np[..., :3] + rays_np[..., 3:] * t_hit[..., None] |
| return hits[sm].reshape(-1, 3).astype(np.float32) |
|
|
|
|
| def raycast_static_multiview(static_centers: np.ndarray, |
| static_sizes: np.ndarray, |
| poses_c2w_views: np.ndarray, |
| K: np.ndarray, |
| H: int, W: int, |
| max_depth: float = 200.0 |
| ) -> np.ndarray: |
| """Depth-derived static PC visible from a set of camera views (union). |
| |
| Mirrors SPMEM's ``voxels_to_depth_pointcloud``: raycast the **static** voxel |
| cubes from several viewpoints sampled uniformly across the trajectory and |
| union the first-hit surface points. This yields a depth-sensor-like cloud |
| that covers everything the camera eventually sees — not just frame 0. |
| |
| No dynamic occluders are added: the static background hidden behind a moving |
| object from one view is still captured from other views, and gets coloured |
| later by the per-chunk progressive coloring. Hits are un-deduped; the caller |
| voxel-downsamples. |
| """ |
| import open3d.core as o3c |
|
|
| static_v, static_f = build_cube_triangle_mesh(static_centers, static_sizes) |
| scene, static_id, _ = _build_scene_for_frame( |
| static_v, static_f, |
| np.zeros((0, 3), dtype=np.float32), |
| np.zeros((0,), dtype=np.float32), |
| ) |
| if scene is None or static_id < 0: |
| return np.zeros((0, 3), dtype=np.float32) |
|
|
| intrinsic = o3c.Tensor(K.astype(np.float64), dtype=o3c.float64) |
| views = np.asarray(poses_c2w_views, dtype=np.float64) |
| if views.ndim == 2: |
| views = views[None, ...] |
|
|
| all_hits: List[np.ndarray] = [] |
| for c2w in views: |
| w2c = np.linalg.inv(c2w) |
| rays = scene.create_rays_pinhole( |
| intrinsic_matrix=intrinsic, |
| extrinsic_matrix=o3c.Tensor(w2c, dtype=o3c.float64), |
| width_px=W, height_px=H, |
| ) |
| ans = scene.cast_rays(rays) |
| t_hit = ans["t_hit"].numpy() |
| geom_ids = ans["geometry_ids"].numpy() |
| valid = (np.isfinite(t_hit) & (t_hit > 1e-3) |
| & (t_hit < max_depth) & (geom_ids == static_id)) |
| if not valid.any(): |
| continue |
| rays_np = rays.numpy() |
| hits = rays_np[..., :3] + rays_np[..., 3:] * t_hit[..., None] |
| all_hits.append(hits[valid].reshape(-1, 3).astype(np.float32)) |
|
|
| if not all_hits: |
| return np.zeros((0, 3), dtype=np.float32) |
| return np.concatenate(all_hits, axis=0) |
|
|
|
|
| def _project_points_uvz(points_world: np.ndarray, |
| c2w: np.ndarray, |
| K: np.ndarray, |
| H: int, W: int, |
| max_depth: float = 200.0 |
| ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: |
| """Project (N, 3) points into camera ``c2w``. Returns ``(u_i, v_i, z, valid)`` |
| arrays of shape ``(N,)``. ``valid`` is the in-view & in-front mask.""" |
| if len(points_world) == 0: |
| empty_i = np.zeros((0,), dtype=np.int64) |
| empty_f = np.zeros((0,), dtype=np.float32) |
| empty_b = np.zeros((0,), dtype=bool) |
| return empty_i, empty_i, empty_f, empty_b |
|
|
| w2c = np.linalg.inv(c2w.astype(np.float64)).astype(np.float32) |
| R, t = w2c[:3, :3], w2c[:3, 3] |
| pts_cam = points_world.astype(np.float32) @ R.T + t |
| z = pts_cam[:, 2] |
| safe_z = np.where(z > 1e-6, z, 1.0) |
| fx, fy = float(K[0, 0]), float(K[1, 1]) |
| cx, cy = float(K[0, 2]), float(K[1, 2]) |
| u_f = pts_cam[:, 0] / safe_z * fx + cx |
| v_f = pts_cam[:, 1] / safe_z * fy + cy |
| u_i = np.rint(u_f).astype(np.int64) |
| v_i = np.rint(v_f).astype(np.int64) |
| valid = ( |
| (z > 1e-3) & (z < max_depth) |
| & np.isfinite(u_f) & np.isfinite(v_f) |
| & (u_i >= 0) & (u_i < W) & (v_i >= 0) & (v_i < H) |
| ) |
| return u_i, v_i, z.astype(np.float32), valid |
|
|
|
|
| def sample_pc_colors_from_image(points_world: np.ndarray, |
| c2w: np.ndarray, |
| K: np.ndarray, |
| image_rgb: np.ndarray, |
| fg_mask: Optional[np.ndarray] = None, |
| default_color: Tuple[int, int, int] = (128, 128, 128), |
| max_depth: float = 200.0, |
| return_keep_mask: bool = False): |
| """Sample per-point RGB from ``image_rgb`` at where each point projects. |
| |
| Points that fall outside the view, behind the camera, or onto pixels |
| where ``fg_mask`` is ``True`` get ``default_color`` instead. Returns |
| ``(N, 3) uint8`` colors; if ``return_keep_mask`` is True, also returns |
| a ``(N,) bool`` mask that is True exactly for points that successfully |
| sampled a real color (in-view AND not masked out). |
| """ |
| H, W = image_rgb.shape[:2] |
| N = len(points_world) |
| out = np.tile(np.array(default_color, dtype=np.uint8), (N, 1)) |
| keep = np.zeros(N, dtype=bool) |
| if N == 0: |
| return (out, keep) if return_keep_mask else out |
| u_i, v_i, _, valid = _project_points_uvz(points_world, c2w, K, H, W, max_depth) |
| if not valid.any(): |
| return (out, keep) if return_keep_mask else out |
| sampled = image_rgb[v_i[valid], u_i[valid]] |
| if fg_mask is not None: |
| on_fg = fg_mask[v_i[valid], u_i[valid]].astype(bool) |
| ok = ~on_fg |
| idx_valid = np.nonzero(valid)[0] |
| out[idx_valid[ok]] = sampled[ok] |
| keep[idx_valid[ok]] = True |
| else: |
| out[valid] = sampled |
| keep[valid] = True |
| return (out, keep) if return_keep_mask else out |
|
|
|
|
| def color_points_from_first_frame(points_frame0: np.ndarray, |
| c2w_0: np.ndarray, |
| K: np.ndarray, |
| first_rgb: np.ndarray, |
| fg_mask: Optional[np.ndarray] = None, |
| ) -> Tuple[np.ndarray, np.ndarray]: |
| """Sample per-point RGB from ``first_rgb`` at each point's camera-0 projection. |
| |
| Points that (a) project outside the camera, or (b) land outside |
| ``fg_mask`` (when provided) are flagged as un-colored. |
| |
| Returns ``(point_color (N, 3) uint8, point_has_color (N,) bool)``. |
| """ |
| N = len(points_frame0) |
| point_color = np.zeros((N, 3), dtype=np.uint8) |
| point_has_color = np.zeros(N, dtype=bool) |
| if N == 0: |
| return point_color, point_has_color |
| H, W = first_rgb.shape[:2] |
| u_i, v_i, _, valid = _project_points_uvz(points_frame0, c2w_0, K, H, W) |
| if not valid.any(): |
| return point_color, point_has_color |
| sampled = first_rgb[v_i[valid], u_i[valid]] |
| if fg_mask is not None: |
| in_fg = fg_mask[v_i[valid], u_i[valid]].astype(bool) |
| ok = in_fg |
| else: |
| ok = np.ones(int(valid.sum()), dtype=bool) |
| idx_valid = np.nonzero(valid)[0] |
| point_color[idx_valid[ok]] = sampled[ok] |
| point_has_color[idx_valid[ok]] = True |
| return point_color, point_has_color |
|
|
|
|
| def project_pc_zbuffer_depth(points_world: np.ndarray, |
| c2w: np.ndarray, |
| K: np.ndarray, |
| H: int, W: int, |
| max_depth: float = 200.0) -> np.ndarray: |
| """LiveWorld-style point splat: each 3-D point → 1 pixel, z-buffer keeps |
| the closest one. Returns an ``(H, W)`` depth map (``np.inf`` where no |
| point projected). |
| |
| This mirrors ``LiveWorld/scripts/create_train_data/_projection.py:: |
| _compute_zbuffer`` — the very same projection the diffusion model sees |
| after VAE encoding. |
| """ |
| out = np.full((H, W), np.inf, dtype=np.float32) |
| if len(points_world) == 0: |
| return out |
|
|
| u_i, v_i, z, valid = _project_points_uvz(points_world, c2w, K, H, W, max_depth) |
| if not valid.any(): |
| return out |
|
|
| flat = (v_i[valid] * W + u_i[valid]).astype(np.int64) |
| z_val = z[valid].astype(np.float32) |
| order = np.argsort(z_val) |
| flat_sorted = flat[order] |
| z_sorted = z_val[order] |
| unique_flat, first_idx = np.unique(flat_sorted, return_index=True) |
| flat_buf = np.full(H * W, np.inf, dtype=np.float32) |
| flat_buf[unique_flat] = z_sorted[first_idx] |
| return flat_buf.reshape(H, W) |
|
|
|
|
| def project_pc_zbuffer_rgb(points_world: np.ndarray, |
| colors_uint8: np.ndarray, |
| c2w: np.ndarray, |
| K: np.ndarray, |
| H: int, W: int, |
| max_depth: float = 200.0, |
| bg_rgb: Tuple[int, int, int] = (0, 0, 0), |
| splat_size: int = 1, |
| ) -> np.ndarray: |
| """LiveWorld-style point splat with **per-point RGB colors**: each point |
| paints a ``splat_size × splat_size`` block of pixels with its color; |
| z-buffer keeps the closest point per pixel. Pixels with no point retain |
| ``bg_rgb``. Returns ``(H, W, 3) uint8``. |
| |
| ``splat_size=1`` (default) → exact LiveWorld behaviour (1 pixel per |
| point). ``splat_size=2`` fills typical 1cm-grid moiré gaps from oblique |
| angles at ~4× the splat cost. |
| """ |
| out = np.tile(np.array(bg_rgb, dtype=np.uint8), (H, W, 1)) |
| if len(points_world) == 0: |
| return out |
|
|
| u_i, v_i, z, valid = _project_points_uvz(points_world, c2w, K, H, W, max_depth) |
| if not valid.any(): |
| return out |
|
|
| u_v = u_i[valid] |
| v_v = v_i[valid] |
| z_v = z[valid].astype(np.float32) |
| c_v = colors_uint8[valid].astype(np.uint8) |
|
|
| if splat_size > 1: |
| |
| |
| offsets = np.array( |
| [(du, dv) for du in range(splat_size) for dv in range(splat_size)], |
| dtype=np.int64, |
| ) |
| N_off = len(offsets) |
| u_v = np.repeat(u_v, N_off) + np.tile(offsets[:, 0], len(z_v)) |
| v_v = np.repeat(v_v, N_off) + np.tile(offsets[:, 1], len(z_v)) |
| z_v = np.repeat(z_v, N_off) |
| c_v = np.repeat(c_v, N_off, axis=0) |
| inb = (u_v >= 0) & (u_v < W) & (v_v >= 0) & (v_v < H) |
| u_v = u_v[inb] |
| v_v = v_v[inb] |
| z_v = z_v[inb] |
| c_v = c_v[inb] |
| if len(z_v) == 0: |
| return out |
|
|
| flat = (v_v * W + u_v).astype(np.int64) |
| order = np.argsort(z_v) |
| flat_sorted = flat[order] |
| cols_sorted = c_v[order] |
| unique_flat, first_idx = np.unique(flat_sorted, return_index=True) |
| rgb_flat = out.reshape(H * W, 3).copy() |
| rgb_flat[unique_flat] = cols_sorted[first_idx] |
| return rgb_flat.reshape(H, W, 3) |
|
|
|
|
| def render_pc_video_depth(pc_or_dict, |
| poses_c2w: np.ndarray, |
| K: np.ndarray, |
| H: int, W: int, |
| *, |
| is_static: bool, |
| max_depth: float = 200.0) -> np.ndarray: |
| """Project a PC through every camera in ``poses_c2w`` via z-buffer splat. |
| |
| - If ``is_static`` is ``True``, ``pc_or_dict`` is a ``(M, 3)`` array and |
| the same PC is projected every frame. |
| - Else, ``pc_or_dict`` is a ``Dict[int, (Mt, 3)]`` of per-frame PCs. |
| |
| Returns ``(T, H, W)`` float depth (``np.inf`` at uncovered pixels). |
| """ |
| T = len(poses_c2w) |
| out = np.full((T, H, W), np.inf, dtype=np.float32) |
| for t in range(T): |
| if is_static: |
| pts = pc_or_dict |
| else: |
| pts = pc_or_dict.get(t, np.zeros((0, 3), dtype=np.float32)) |
| if len(pts) == 0: |
| continue |
| out[t] = project_pc_zbuffer_depth(pts, poses_c2w[t], K, H, W, max_depth) |
| return out |
|
|
|
|
| def render_pc_video_rgb(pc_or_dict, |
| colors_or_dict, |
| poses_c2w: np.ndarray, |
| K: np.ndarray, |
| H: int, W: int, |
| *, |
| is_static: bool, |
| max_depth: float = 200.0, |
| splat_size: int = 1) -> np.ndarray: |
| """Like :func:`render_pc_video_depth` but writes RGB per-point colors. |
| |
| - ``is_static=True``: ``pc_or_dict`` is ``(M, 3)`` and ``colors_or_dict`` |
| is ``(M, 3)``; the same colored PC is projected every frame. |
| - ``is_static=False``: both are ``Dict[int, ndarray]`` keyed by frame. |
| |
| ``splat_size`` is forwarded to :func:`project_pc_zbuffer_rgb`. |
| Returns ``(T, H, W, 3) uint8``. |
| """ |
| T = len(poses_c2w) |
| out = np.zeros((T, H, W, 3), dtype=np.uint8) |
| for t in range(T): |
| if is_static: |
| pts = pc_or_dict |
| cols = colors_or_dict |
| else: |
| pts = pc_or_dict.get(t, np.zeros((0, 3), dtype=np.float32)) |
| cols = colors_or_dict.get(t, np.zeros((0, 3), dtype=np.uint8)) |
| if len(pts) == 0: |
| continue |
| out[t] = project_pc_zbuffer_rgb( |
| pts, cols, poses_c2w[t], K, H, W, max_depth, |
| splat_size=splat_size, |
| ) |
| return out |
|
|
|
|
| |
| |
| |
|
|
| def depth_to_grayscale_frames(depths: np.ndarray, |
| percentile: Tuple[float, float] = (2.0, 98.0), |
| colormap: Optional[int] = None) -> np.ndarray: |
| """Convert (T, H, W) float depth to (T, H, W, 3) uint8 RGB frames. |
| |
| Near pixels are bright, far are dim, no-hit (inf) is black. Depth range is |
| derived from percentile clipping across all valid pixels in the stack so |
| every frame uses the same brightness mapping. |
| """ |
| valid_mask = np.isfinite(depths) |
| if not valid_mask.any(): |
| return np.zeros((*depths.shape, 3), dtype=np.uint8) |
| valid_d = depths[valid_mask] |
| near = float(np.percentile(valid_d, percentile[0])) |
| far = float(np.percentile(valid_d, percentile[1])) |
| if far <= near: |
| far = near + 1.0 |
|
|
| norm = np.clip((depths - near) / (far - near), 0.0, 1.0) |
| gray = ((1.0 - norm) * 255).astype(np.uint8) |
| gray[~valid_mask] = 0 |
|
|
| if colormap is None: |
| return np.stack([gray, gray, gray], axis=-1) |
|
|
| out = np.empty((*depths.shape, 3), dtype=np.uint8) |
| for t in range(depths.shape[0]): |
| rgb = cv2.applyColorMap(gray[t], colormap) |
| rgb = cv2.cvtColor(rgb, cv2.COLOR_BGR2RGB) |
| rgb[~valid_mask[t]] = 0 |
| out[t] = rgb |
| return out |
|
|
|
|
| def _resolve_ffmpeg_binary() -> Optional[str]: |
| """Locate an ffmpeg binary, preferring system ffmpeg, falling back to |
| the one bundled with ``imageio_ffmpeg`` (always installed in xfuser env). |
| """ |
| import shutil as _sh |
| bin_path = _sh.which("ffmpeg") |
| if bin_path: |
| return bin_path |
| try: |
| import imageio_ffmpeg |
| return imageio_ffmpeg.get_ffmpeg_exe() |
| except Exception: |
| return None |
|
|
|
|
| def save_video_mp4(path: Path, |
| frames: np.ndarray, |
| fps: float = 16.0) -> None: |
| """Write ``(T, H, W, 3) uint8`` RGB frames as MP4 (H.264, yuv420p, |
| +faststart) via ffmpeg subprocess — same recipe as |
| ``liveworld.utils.save_video_h264``. Falls back to ``cv2.VideoWriter`` |
| only if no ffmpeg binary is reachable. |
| |
| Why not cv2's mp4v writer? It writes raw RGB into an MPEG-4 Part 2 |
| container without proper YUV color-space conversion. Many players |
| (Cursor's preview, Chrome, QuickTime) interpret the resulting frames as |
| YUV420 and render them as a uniform green tint. Using libx264 + |
| yuv420p + faststart is the universal MP4 recipe. |
| """ |
| import subprocess |
|
|
| p = Path(path) |
| p.parent.mkdir(parents=True, exist_ok=True) |
| if frames.size == 0: |
| return |
| if frames.dtype != np.uint8: |
| frames = frames.astype(np.uint8) |
| T, H, W, C = frames.shape |
| if C != 3: |
| raise ValueError(f"save_video_mp4 expects (T, H, W, 3) RGB; got {frames.shape}") |
|
|
| ffmpeg_bin = _resolve_ffmpeg_binary() |
| if ffmpeg_bin is not None: |
| cmd = [ |
| ffmpeg_bin, "-y", |
| "-f", "rawvideo", |
| "-pix_fmt", "rgb24", |
| "-s", f"{W}x{H}", |
| "-r", str(float(fps)), |
| "-i", "-", |
| "-an", |
| "-c:v", "libx264", |
| "-preset", "medium", |
| "-crf", "18", |
| "-pix_fmt", "yuv420p", |
| "-movflags", "+faststart", |
| str(p), |
| ] |
| proc = subprocess.Popen( |
| cmd, stdin=subprocess.PIPE, |
| stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, |
| ) |
| try: |
| assert proc.stdin is not None |
| for i in range(T): |
| proc.stdin.write(frames[i].tobytes()) |
| proc.stdin.close() |
| assert proc.stderr is not None |
| stderr = proc.stderr.read() |
| ret = proc.wait() |
| if ret != 0: |
| raise RuntimeError( |
| f"ffmpeg failed ({ret}) writing {p}:\n" |
| f"{stderr.decode('utf-8', 'replace')}" |
| ) |
| except Exception: |
| proc.kill() |
| raise |
| return |
|
|
| |
| print(f"[warn] ffmpeg not found; falling back to cv2 mp4v writer for {p}") |
| fourcc = cv2.VideoWriter_fourcc(*"mp4v") |
| writer = cv2.VideoWriter(str(p), fourcc, float(fps), (W, H)) |
| if not writer.isOpened(): |
| raise RuntimeError(f"cv2.VideoWriter failed to open: {p}") |
| for f in frames: |
| writer.write(cv2.cvtColor(f, cv2.COLOR_RGB2BGR)) |
| writer.release() |
|
|
|
|
| |
| |
| |
|
|
| @dataclass |
| class VoxelChunk: |
| centers: np.ndarray |
| sizes: np.ndarray |
|
|
|
|
| def _collect_static_voxels(static_npz_path: Path, |
| objects_info: Dict[str, dict], |
| default_voxel_size: float, |
| voxel_size_scale: float) -> VoxelChunk: |
| if not static_npz_path.exists(): |
| raise FileNotFoundError(f"static.npz not found: {static_npz_path}") |
| npz = np.load(static_npz_path) |
| try: |
| centers_chunks, size_chunks = [], [] |
| for name in npz.files: |
| info = objects_info.get(name, {}) |
| if info.get("type") != "static": |
| continue |
| pts = npz[name].astype(np.float32) |
| if pts.size == 0: |
| continue |
| vs = float(info.get("voxel_size", default_voxel_size)) * voxel_size_scale |
| centers_chunks.append(pts) |
| size_chunks.append(np.full(pts.shape[0], vs, dtype=np.float32)) |
| finally: |
| npz.close() |
| if not centers_chunks: |
| return VoxelChunk(np.zeros((0, 3), np.float32), np.zeros((0,), np.float32)) |
| return VoxelChunk( |
| np.concatenate(centers_chunks, axis=0), |
| np.concatenate(size_chunks, axis=0), |
| ) |
|
|
|
|
| def _collect_dyn_voxels_for_frame(ved_dir: Path, |
| frame_meta: dict, |
| objects_info: Dict[str, dict], |
| default_voxel_size: float, |
| voxel_size_scale: float) -> VoxelChunk: |
| npz_path = ved_dir / frame_meta["data_file"] |
| if not npz_path.exists(): |
| return VoxelChunk(np.zeros((0, 3), np.float32), np.zeros((0,), np.float32)) |
| npz = np.load(npz_path) |
| centers_chunks, size_chunks = [], [] |
| try: |
| for name in npz.files: |
| info = objects_info.get(name, {}) |
| if info.get("type") != "dynamic": |
| continue |
| pts = npz[name].astype(np.float32) |
| if pts.size == 0: |
| continue |
| vs = float(info.get("voxel_size", default_voxel_size)) * voxel_size_scale |
| centers_chunks.append(pts) |
| size_chunks.append(np.full(pts.shape[0], vs, dtype=np.float32)) |
| finally: |
| npz.close() |
| if not centers_chunks: |
| return VoxelChunk(np.zeros((0, 3), np.float32), np.zeros((0,), np.float32)) |
| return VoxelChunk( |
| np.concatenate(centers_chunks, axis=0), |
| np.concatenate(size_chunks, axis=0), |
| ) |
|
|
|
|
| def _collect_dyn_per_object_persistent(ved_dir: Path, |
| frames_meta: List[dict], |
| objects_info: Dict[str, dict], |
| default_voxel_size: float, |
| voxel_size_scale: float, |
| n_use: int |
| ) -> Tuple[Dict[int, np.ndarray], |
| Dict[int, np.ndarray], |
| np.ndarray, |
| List[str]]: |
| """Collect dyn voxels per frame with **persistent per-voxel identity**. |
| |
| Unlike :func:`_collect_dyn_voxels_for_frame` (which iterates ``npz.files`` |
| in arbitrary order and then dedups), this function: |
| |
| - Iterates dynamic object names in a deterministic (alphabetical) order |
| so the row layout of the returned ``(K_total, 3)`` array is identical |
| across frames. |
| - Skips dedup so row ``i`` in frame ``t`` is the same physical voxel as |
| row ``i`` in frame ``0`` (per-object index → global combined index). |
| - Verifies that every frame has the same ``K_total`` and same per-object |
| counts; raises if the upstream data breaks identity. |
| |
| Returns: |
| ``(centers_per_frame, sizes_per_frame, voxel_obj_id, dyn_names)`` |
| where ``voxel_obj_id`` is ``(K_total,) int32`` indexing into |
| ``dyn_names`` (same array reused for every frame). |
| """ |
| dyn_names = sorted( |
| n for n, info in objects_info.items() if info.get("type") == "dynamic" |
| ) |
| centers_per_frame: Dict[int, np.ndarray] = {} |
| sizes_per_frame: Dict[int, np.ndarray] = {} |
| K_total_ref: Optional[int] = None |
| voxel_obj_id_ref: Optional[np.ndarray] = None |
| per_obj_count_ref: Optional[List[int]] = None |
|
|
| for t in range(n_use): |
| fm = frames_meta[t] |
| npz_path = ved_dir / fm["data_file"] |
| if not npz_path.exists(): |
| raise FileNotFoundError(f"missing dyn voxel npz: {npz_path}") |
| per_obj_centers: List[np.ndarray] = [] |
| per_obj_sizes: List[np.ndarray] = [] |
| per_obj_id: List[np.ndarray] = [] |
| per_obj_count: List[int] = [] |
| npz = np.load(npz_path) |
| try: |
| for obj_idx, name in enumerate(dyn_names): |
| if name in npz.files and npz[name].size: |
| arr = npz[name].astype(np.float32) |
| else: |
| arr = np.zeros((0, 3), dtype=np.float32) |
| vs = float( |
| objects_info[name].get("voxel_size", default_voxel_size) |
| ) * voxel_size_scale |
| per_obj_centers.append(arr) |
| per_obj_sizes.append(np.full(len(arr), vs, dtype=np.float32)) |
| per_obj_id.append(np.full(len(arr), obj_idx, dtype=np.int32)) |
| per_obj_count.append(len(arr)) |
| finally: |
| npz.close() |
| centers = (np.concatenate(per_obj_centers, axis=0) |
| if per_obj_centers else np.zeros((0, 3), dtype=np.float32)) |
| sizes = (np.concatenate(per_obj_sizes, axis=0) |
| if per_obj_sizes else np.zeros((0,), dtype=np.float32)) |
| obj_id = (np.concatenate(per_obj_id, axis=0) |
| if per_obj_id else np.zeros((0,), dtype=np.int32)) |
|
|
| if K_total_ref is None: |
| K_total_ref = len(centers) |
| voxel_obj_id_ref = obj_id |
| per_obj_count_ref = per_obj_count |
| else: |
| if len(centers) != K_total_ref or per_obj_count != per_obj_count_ref: |
| raise RuntimeError( |
| f"dyn voxel count mismatch at frame {t}: " |
| f"got per-object {per_obj_count} (total {len(centers)}) vs " |
| f"reference {per_obj_count_ref} (total {K_total_ref}). " |
| "Per-voxel identity is broken — fg color propagation cannot work." |
| ) |
|
|
| centers_per_frame[t] = centers |
| sizes_per_frame[t] = sizes |
|
|
| assert voxel_obj_id_ref is not None |
| return centers_per_frame, sizes_per_frame, voxel_obj_id_ref, dyn_names |
|
|
|
|
| def _voxel_dedup(chunk: VoxelChunk) -> VoxelChunk: |
| if len(chunk.centers) == 0: |
| return chunk |
| keys = np.concatenate( |
| [np.round(chunk.centers, 3), chunk.sizes.reshape(-1, 1).round(4)], axis=1 |
| ) |
| _, unique_idx = np.unique(keys, axis=0, return_index=True) |
| unique_idx.sort() |
| return VoxelChunk(chunk.centers[unique_idx], chunk.sizes[unique_idx]) |
|
|
|
|
| |
| |
| |
|
|
| def render_fg_mask_from_voxels(centers: np.ndarray, |
| sizes: np.ndarray, |
| c2w_opencv: np.ndarray, |
| K: np.ndarray, |
| H: int, W: int, |
| dilate_px: int = 5) -> np.ndarray: |
| """Per-voxel 8-corner projected bbox fill (then dilate).""" |
| mask = np.zeros((H, W), dtype=bool) |
| if len(centers) == 0: |
| return mask |
|
|
| offs = np.array([[a, b, c] for a in (-0.5, 0.5) for b in (-0.5, 0.5) |
| for c in (-0.5, 0.5)], dtype=np.float32) |
| corners_w = (centers[:, None, :] |
| + offs[None, :, :] * sizes[:, None, None]) |
| flat = corners_w.reshape(-1, 3) |
|
|
| w2c = np.linalg.inv(c2w_opencv).astype(np.float32) |
| pts_cam = flat @ w2c[:3, :3].T + w2c[:3, 3] |
| z = pts_cam[:, 2] |
| safe_z = np.where(z > 1e-3, z, 1.0) |
| uv = pts_cam @ K.T |
| u = uv[:, 0] / safe_z |
| v = uv[:, 1] / safe_z |
|
|
| z = z.reshape(-1, 8) |
| u = u.reshape(-1, 8) |
| v = v.reshape(-1, 8) |
| in_front = (z > 1e-3).all(axis=1) |
|
|
| for i in np.nonzero(in_front)[0]: |
| umin = max(0, int(np.floor(u[i].min()))) |
| vmin = max(0, int(np.floor(v[i].min()))) |
| umax = min(W - 1, int(np.ceil(u[i].max()))) |
| vmax = min(H - 1, int(np.ceil(v[i].max()))) |
| if umin > umax or vmin > vmax: |
| continue |
| mask[vmin:vmax + 1, umin:umax + 1] = True |
|
|
| if dilate_px > 0: |
| k = max(1, int(dilate_px)) |
| kernel = np.ones((k, k), np.uint8) |
| mask = cv2.dilate(mask.astype(np.uint8), kernel, iterations=1).astype(bool) |
| return mask |
|
|
|
|
| |
| |
| |
|
|
| def _resolve_metadata_path(voxels_path: Path) -> Path: |
| return voxels_path.parent.parent / "metadata.json" |
|
|
|
|
| def _resolve_ved_dir(voxels_path: Path) -> Path: |
| return voxels_path.parent.parent.parent |
|
|
|
|
| def convert_case(entry: dict, |
| output_root: Path, |
| *, |
| target_w: int, |
| target_h: int, |
| num_frames: Optional[int], |
| viz_num_frames: Optional[int], |
| points_per_voxel: int, |
| dyn_samples_per_voxel: int, |
| voxel_size_scale: float, |
| visibility: str, |
| depth_views: int, |
| z_tol_rel: float, |
| z_tol_abs: float, |
| final_voxel_downsample: float, |
| fg_dilate: int, |
| seed: int, |
| overwrite: bool, |
| save_projection_videos: bool = True, |
| save_bg_projection_video: bool = True, |
| viz_fps: float = 16.0, |
| viz_colormap: str = "turbo") -> Optional[Path]: |
| name = entry["name"] |
| out_dir = output_root / name |
| if out_dir.exists() and not overwrite: |
| if all((out_dir / f).exists() for f in |
| ("first_frame.png", "prompt.txt", "geometry.npz", "pointcloud.npz")): |
| print(f"[skip] {name}: already exists (use --overwrite to redo)") |
| return out_dir |
| out_dir.mkdir(parents=True, exist_ok=True) |
|
|
| print(f"\n=== converting {name} ===") |
|
|
| voxels_path = Path(entry["voxels"]) |
| metadata_path = _resolve_metadata_path(voxels_path) |
| ved_dir = _resolve_ved_dir(voxels_path) |
| input_image = Path(entry["input_image"]) |
| if not metadata_path.exists(): |
| raise FileNotFoundError(f"metadata.json missing: {metadata_path}") |
| if not input_image.exists(): |
| raise FileNotFoundError(f"input_image missing: {input_image}") |
|
|
| metadata = json.loads(metadata_path.read_text(encoding="utf-8")) |
| objects_info: Dict[str, dict] = metadata["objects_info"] |
| frames_meta: List[dict] = metadata["frames"] |
| default_voxel_size = float(metadata.get("voxel_size", 0.25)) |
| static_data_file = metadata.get("static_data_file", "static.npz") |
| static_npz_path = ved_dir / static_data_file |
|
|
| N_total = len(frames_meta) |
| pc_n_use = N_total if num_frames is None else min(int(num_frames), N_total) |
| |
| |
| |
| |
| viz_n_use = (pc_n_use if viz_num_frames is None |
| else min(int(viz_num_frames), N_total)) |
| |
| n_use = max(pc_n_use, viz_n_use) |
| frames_use = frames_meta[:n_use] |
| print(f" pc range: {pc_n_use}/{N_total} frames " |
| f"(saved to geometry.npz; model will iterate to fill this)") |
| print(f" viz range: {viz_n_use}/{N_total} frames " |
| f"(bg/fg projection videos)" |
| + (" [extended beyond PC range]" if viz_n_use > pc_n_use else "")) |
| print(f" raycast spans {n_use} frames") |
|
|
| |
| c2w_blender = np.stack( |
| [np.array(fm["camera_extrinsics"], dtype=np.float32) for fm in frames_use], |
| axis=0, |
| ) |
| poses_c2w = blender_c2w_to_opencv_c2w(c2w_blender) |
| poses_c2w_pc = poses_c2w[:pc_n_use] |
| poses_c2w_viz = poses_c2w[:viz_n_use] |
| fx, fy, cx, cy = compute_intrinsics_px(frames_use[0]["camera_intrinsics"], |
| target_w, target_h) |
| K = K_matrix(fx, fy, cx, cy) |
| intrinsics_size = np.array([target_h, target_w], dtype=np.int32) |
| print(f" K: fx={fx:.2f}, fy={fy:.2f}, cx={cx:.2f}, cy={cy:.2f}") |
|
|
| rng = np.random.default_rng(seed) |
|
|
| |
| static_chunk = _collect_static_voxels( |
| static_npz_path, objects_info, default_voxel_size, voxel_size_scale, |
| ) |
| static_chunk = _voxel_dedup(static_chunk) |
| print(f" static voxels: {len(static_chunk.centers)}") |
|
|
| |
| |
| |
| |
| (dyn_centers_per_frame, dyn_sizes_per_frame, |
| dyn_voxel_obj_id, dyn_obj_names) = _collect_dyn_per_object_persistent( |
| ved_dir, frames_meta, objects_info, |
| default_voxel_size, voxel_size_scale, n_use, |
| ) |
| K_dyn_total = dyn_centers_per_frame[0].shape[0] if n_use else 0 |
| total_dyn_voxels = K_dyn_total * n_use |
| print(f" dyn voxels: {K_dyn_total} voxels x {n_use} frames " |
| f"(objects={dyn_obj_names}; persistent index)") |
|
|
| |
| static_pc_for_viz: np.ndarray = np.zeros((0, 3), dtype=np.float32) |
| dyn_pc_per_frame_rgb: Dict[int, np.ndarray] = {} |
| dyn_colors_per_frame_rgb: Dict[int, np.ndarray] = {} |
|
|
| if visibility == "depth": |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| total_traj = max(1, pc_n_use) |
| n_views = min(max(1, int(depth_views)), total_traj) |
| if n_views <= 1: |
| view_indices = [0] |
| else: |
| view_indices = np.unique( |
| np.linspace(0, total_traj - 1, n_views).round().astype(int) |
| ).tolist() |
| print(f" [depth] static: raycasting {len(view_indices)} views uniformly " |
| f"across {total_traj} frames (target {target_h}x{target_w}, " |
| f"static-only)...") |
| static_pts_raw = raycast_static_multiview( |
| static_chunk.centers, static_chunk.sizes, |
| poses_c2w[view_indices], K, target_h, target_w, |
| ) |
| print(f" [depth] static raw hits: {len(static_pts_raw)}") |
|
|
| |
| |
| |
| _img_pil = Image.open(input_image).convert("RGB") |
| if _img_pil.size != (target_w, target_h): |
| _img_pil = _img_pil.resize((target_w, target_h), Image.LANCZOS) |
| first_rgb_mem = np.asarray(_img_pil, dtype=np.uint8) |
| if K_dyn_total > 0: |
| fg_mask_mem = render_fg_mask_from_voxels( |
| centers=dyn_centers_per_frame[0], |
| sizes=dyn_sizes_per_frame[0], |
| c2w_opencv=poses_c2w[0], K=K, |
| H=target_h, W=target_w, dilate_px=fg_dilate, |
| ) |
| else: |
| fg_mask_mem = None |
|
|
| K_per_voxel = int(dyn_samples_per_voxel) |
| unit_samples = build_unit_cube_surface_samples(K_per_voxel, seed=seed) |
| samples_0 = transform_unit_samples_per_voxel( |
| unit_samples, |
| dyn_centers_per_frame[0], |
| dyn_sizes_per_frame[0], |
| ) |
| print(f" [color] per-point frame-0 colour sampling " |
| f"({K_dyn_total} voxels × {K_per_voxel} samples = " |
| f"{len(samples_0)} pts)...") |
| point_colors, point_has_color = color_points_from_first_frame( |
| samples_0, poses_c2w[0], K, first_rgb_mem, |
| fg_mask=fg_mask_mem, |
| ) |
| n_colored = int(point_has_color.sum()) |
| print(f" [color] -> {n_colored}/{len(samples_0)} surface pts coloured " |
| f"({100.0 * point_has_color.mean():.1f}%)") |
|
|
| print(f" [dyn] skipping raycast; using {n_colored} coloured surface pts " |
| f"× {n_use} frames") |
|
|
| if n_colored > 0: |
| |
| |
| shared_colors = point_colors[point_has_color].astype(np.uint8) |
| for t in range(n_use): |
| samples_t = transform_unit_samples_per_voxel( |
| unit_samples, |
| dyn_centers_per_frame[t], |
| dyn_sizes_per_frame[t], |
| ) |
| dyn_pc_per_frame_rgb[t] = samples_t[point_has_color].astype(np.float32) |
| dyn_colors_per_frame_rgb[t] = shared_colors |
| total_dyn_samples = sum(len(p) for p in dyn_pc_per_frame_rgb.values()) |
|
|
| if final_voxel_downsample <= 0: |
| |
| final_voxel_downsample = 0.01 |
| print(f" [depth] auto-setting --final-voxel-downsample to " |
| f"{final_voxel_downsample} m") |
|
|
| static_pc_for_viz = voxel_downsample_points( |
| static_pts_raw, final_voxel_downsample |
| ) |
|
|
| |
| |
| |
| |
| points = static_pc_for_viz |
| print(f" [depth] downsample @ {final_voxel_downsample} m: " |
| f"static-only PC {len(points)} pts " |
| f"(views={len(view_indices)}; dyn samples kept only for fg viz: " |
| f"{total_dyn_samples})") |
| else: |
| |
| static_pts, static_normals = sample_cube_surface_points( |
| static_chunk.centers, static_chunk.sizes, points_per_voxel, rng, |
| return_normals=True, |
| ) |
| dyn_pts_per_frame: Dict[int, np.ndarray] = {} |
| dyn_normals_per_frame: Dict[int, np.ndarray] = {} |
| for t in range(n_use): |
| c = dyn_centers_per_frame[t] |
| s = dyn_sizes_per_frame[t] |
| if len(c) == 0: |
| dyn_pts_per_frame[t] = np.zeros((0, 3), np.float32) |
| dyn_normals_per_frame[t] = np.zeros((0, 3), np.float32) |
| else: |
| p, n = sample_cube_surface_points(c, s, points_per_voxel, rng, |
| return_normals=True) |
| dyn_pts_per_frame[t] = p |
| dyn_normals_per_frame[t] = n |
|
|
| if visibility == "none": |
| static_keep = np.ones(len(static_pts), dtype=bool) |
| dyn_keeps = {t: np.ones(len(p), dtype=bool) |
| for t, p in dyn_pts_per_frame.items()} |
| elif visibility == "backface": |
| cam_positions = poses_c2w[:, :3, 3] |
| static_keep = cull_back_faces(static_pts, static_normals, cam_positions) |
| dyn_keeps = {} |
| for t, p in dyn_pts_per_frame.items(): |
| if len(p) == 0: |
| dyn_keeps[t] = np.zeros(0, dtype=bool) |
| else: |
| dyn_keeps[t] = cull_back_faces( |
| p, dyn_normals_per_frame[t], poses_c2w[t:t + 1, :3, 3], |
| ) |
| else: |
| raise ValueError(f"--visibility must be 'none'|'backface'|'depth', " |
| f"got {visibility}") |
|
|
| final_static = static_pts[static_keep] |
| final_dyn_chunks = [dyn_pts_per_frame[t][dyn_keeps[t]] |
| for t in sorted(dyn_pts_per_frame)] |
| final_dyn_chunks = [c for c in final_dyn_chunks if len(c) > 0] |
| final_dyn = (np.concatenate(final_dyn_chunks, axis=0) |
| if final_dyn_chunks else np.zeros((0, 3), dtype=np.float32)) |
| points = np.concatenate([final_static, final_dyn], axis=0) |
| total_dyn_pts = sum(len(p) for p in dyn_pts_per_frame.values()) |
| print(f" [{visibility}] kept static: {len(final_static)}/{len(static_pts)}, " |
| f"dyn: {len(final_dyn)}/{total_dyn_pts}") |
| if final_voxel_downsample > 0: |
| before = len(points) |
| points = voxel_downsample_points(points, final_voxel_downsample) |
| print(f" downsample @ {final_voxel_downsample} m: {before} → {len(points)}") |
|
|
| print(f" final PC: {points.shape[0]} pts") |
|
|
| |
| img = Image.open(input_image).convert("RGB") |
| if img.size != (target_w, target_h): |
| img = img.resize((target_w, target_h), Image.LANCZOS) |
| img.save(out_dir / "first_frame.png") |
|
|
| |
| dyn_first = _collect_dyn_voxels_for_frame( |
| ved_dir, frames_meta[0], objects_info, default_voxel_size, voxel_size_scale, |
| ) |
| if len(dyn_first.centers) > 0: |
| fg_mask = render_fg_mask_from_voxels( |
| centers=dyn_first.centers, sizes=dyn_first.sizes, |
| c2w_opencv=poses_c2w[0], K=K, |
| H=target_h, W=target_w, dilate_px=fg_dilate, |
| ) |
| cv2.imwrite(str(out_dir / "fg_mask_first.png"), |
| (fg_mask.astype(np.uint8) * 255)) |
| print(f" fg_mask coverage: {fg_mask.mean():.3%}") |
| else: |
| print(" fg_mask: no dynamic voxels in frame 1 → skipped") |
|
|
| |
| (out_dir / "prompt.txt").write_text(entry["prompt"].strip() + "\n", encoding="utf-8") |
|
|
| |
| np.savez_compressed( |
| out_dir / "geometry.npz", |
| poses_c2w=poses_c2w_pc.astype(np.float32), |
| K=K.astype(np.float32), |
| intrinsics_size=intrinsics_size, |
| ) |
| np.savez_compressed(out_dir / "pointcloud.npz", points=points.astype(np.float32)) |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| if save_projection_videos and visibility == "depth": |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| if save_bg_projection_video: |
| first_rgb = np.asarray( |
| Image.open(out_dir / "first_frame.png").convert("RGB"), |
| dtype=np.uint8, |
| ) |
| fg_mask_path = out_dir / "fg_mask_first.png" |
| fg_mask_bool: Optional[np.ndarray] = None |
| if fg_mask_path.exists(): |
| m = cv2.imread(str(fg_mask_path), cv2.IMREAD_GRAYSCALE) |
| if m is not None: |
| fg_mask_bool = m > 0 |
|
|
| print(f" [viz] sampling bg colors from first_frame " |
| f"({len(static_pc_for_viz)} pts; fg region masked, " |
| f"uncolored points dropped)...") |
| bg_colors_full, bg_keep = sample_pc_colors_from_image( |
| static_pc_for_viz, poses_c2w[0], K, |
| first_rgb, fg_mask=fg_mask_bool, return_keep_mask=True, |
| ) |
| bg_pts_colored = static_pc_for_viz[bg_keep] |
| bg_cols_colored = bg_colors_full[bg_keep] |
| print(f" [viz] kept {len(bg_pts_colored)}/{len(static_pc_for_viz)} " |
| f"static pts that successfully sampled a color " |
| f"({100.0 * bg_keep.mean():.1f}%)") |
| print(f" [viz] z-buffer splat bg PC through {viz_n_use} cameras " |
| f"(splat 2x2)...") |
| bg_frames = render_pc_video_rgb( |
| bg_pts_colored, bg_cols_colored, |
| poses_c2w_viz, K, target_h, target_w, is_static=True, |
| splat_size=2, |
| ) |
| bg_path = out_dir / "bg_projection.mp4" |
| save_video_mp4(bg_path, bg_frames, fps=viz_fps) |
| nz_bg = (bg_frames.reshape(bg_frames.shape[0], -1, 3).sum(-1) > 0).mean() |
| print(f" [viz] -> {bg_path} " |
| f"({bg_frames.shape[0]} frames @ {viz_fps} fps, " |
| f"non-empty pixels avg {100.0 * nz_bg:.1f}%)") |
| else: |
| print(" [viz] bg_projection.mp4 skipped " |
| "(scene uses runtime point-cloud splat2d)") |
|
|
| |
| |
| |
| |
| |
| |
| n_dyn_samples_total = sum(len(p) for p in dyn_pc_per_frame_rgb.values()) |
| |
| |
| dyn_viz_pts = {t: dyn_pc_per_frame_rgb.get( |
| t, np.zeros((0, 3), dtype=np.float32)) |
| for t in range(viz_n_use)} |
| dyn_viz_cols = {t: dyn_colors_per_frame_rgb.get( |
| t, np.zeros((0, 3), dtype=np.uint8)) |
| for t in range(viz_n_use)} |
| print(f" [viz] fg: {n_dyn_samples_total} sampled pts across " |
| f"{len(dyn_pc_per_frame_rgb)} frames (all already coloured)") |
| print(f" [viz] z-buffer splat fg PC through {viz_n_use} cameras " |
| f"(splat 2x2)...") |
| fg_frames = render_pc_video_rgb( |
| dyn_viz_pts, dyn_viz_cols, |
| poses_c2w_viz, K, target_h, target_w, is_static=False, |
| splat_size=2, |
| ) |
| fg_path = out_dir / "fg_projection.mp4" |
| save_video_mp4(fg_path, fg_frames, fps=viz_fps) |
| nz_fg = (fg_frames.reshape(fg_frames.shape[0], -1, 3).sum(-1) > 0).mean() |
| print(f" [viz] -> {fg_path} " |
| f"({fg_frames.shape[0]} frames @ {viz_fps} fps, " |
| f"non-empty pixels avg {100.0 * nz_fg:.1f}%)") |
| elif save_projection_videos: |
| print(" [viz] skipped (projection videos only supported for " |
| "--visibility depth)") |
|
|
| print(f" -> {out_dir}") |
| return out_dir |
|
|
|
|
| |
| |
| |
|
|
| def _parse_args() -> argparse.Namespace: |
| p = argparse.ArgumentParser(description="Convert mine_blender voxel exports to LiveWorld_comp inputs (depth-derived PC)") |
| p.add_argument("--meta", required=True, help="Path to meta_long_updated.json") |
| p.add_argument("--output-root", required=True) |
| p.add_argument("--names", nargs="*", default=None, |
| help="Only convert these entry names (default: all)") |
| p.add_argument("--target-w", type=int, default=TARGET_W_DEFAULT) |
| p.add_argument("--target-h", type=int, default=TARGET_H_DEFAULT) |
| p.add_argument("--num-frames", type=int, default=None, |
| help="Number of frames the model will generate " |
| "(default: use all frames in metadata). Saved as " |
| "geometry.npz's poses_c2w and used to scope the dyn " |
| "voxels included in pointcloud.npz.") |
| p.add_argument("--viz-num-frames", type=int, default=None, |
| help="Number of frames in the bg/fg projection videos. " |
| "Defaults to --num-frames so previews stay aligned " |
| "with the model's actual generation range. Set to a " |
| "larger value (e.g. metadata full length) only when " |
| "you want to inspect the full trajectory beyond what " |
| "the model will generate — this preview will then NOT " |
| "correspond 1:1 to model output. Raycast scope = " |
| "max(--num-frames, --viz-num-frames).") |
| p.add_argument("--points-per-voxel", type=int, default=48, |
| help="(legacy/debug modes only) Surface samples per " |
| "voxel for --visibility none|backface.") |
| p.add_argument("--dyn-samples-per-voxel", type=int, default=96, |
| help="(depth mode) Number of surface samples per coloured " |
| "dyn voxel used to build the per-frame dyn PC without " |
| "raycasting. Default 96 ≈ 16/face — denser = smoother " |
| "fg viz / model input but slower splat. Drop to 48 if " |
| "you want closer parity with the legacy raycast output.") |
| p.add_argument("--voxel-size-scale", type=float, default=1.0) |
| p.add_argument("--depth-views", type=int, default=10, |
| help="(depth mode) Number of camera views, sampled uniformly " |
| "across the model's generation range, used to raycast " |
| "the STATIC voxels into a depth-derived background point " |
| "cloud (matches SPMEM's --depth_views). 1 = frame-0 only. " |
| "Default 20.") |
| p.add_argument("--visibility", choices=["none", "backface", "depth"], default="depth", |
| help="none: keep all faces (legacy); " |
| "backface: cull faces facing away from every cam (fast); " |
| "depth: per-frame z-buffer culling (depth-sensor-like, default)") |
| p.add_argument("--z-tol-rel", type=float, default=0.005, |
| help="Relative z-buffer tolerance (frac of ref_z)") |
| p.add_argument("--z-tol-abs", type=float, default=0.01, |
| help="Absolute z-buffer tolerance in metres") |
| p.add_argument("--final-voxel-downsample", type=float, default=0.0, |
| help="Optional final voxel downsample in metres (0 = off)") |
| p.add_argument("--fg-dilate", type=int, default=5) |
| p.add_argument("--seed", type=int, default=0) |
| p.add_argument("--overwrite", action="store_true") |
| p.add_argument("--limit", type=int, default=None) |
| p.add_argument("--indices", type=int, nargs="*", default=None, |
| help="Pick specific meta entries by 0-based index (e.g. " |
| "--indices 0 3 5). Applied after --names filtering, " |
| "before --limit.") |
| p.add_argument("--no-projection-videos", action="store_true", |
| help="Skip writing bg_projection.mp4 / fg_projection.mp4") |
| p.add_argument("--no-bg-projection-video", action="store_true", |
| help="Skip only bg_projection.mp4 (the slow full-cloud " |
| "splat). Safe for the default workflow, where the scene " |
| "is rendered from the point cloud at inference time; " |
| "bg_projection.mp4 is only needed for " |
| "condition_source='mp4'. fg_projection.mp4 is still written.") |
| p.add_argument("--viz-fps", type=float, default=16.0) |
| p.add_argument("--viz-colormap", default="turbo", |
| choices=["turbo", "jet", "magma", "viridis", "gray", "grey"]) |
| return p.parse_args() |
|
|
|
|
| def main() -> None: |
| args = _parse_args() |
| meta_path = Path(args.meta) |
| if not meta_path.exists(): |
| raise SystemExit(f"meta not found: {meta_path}") |
|
|
| meta = json.loads(meta_path.read_text(encoding="utf-8")) |
| if args.names: |
| wanted = set(args.names) |
| entries = [e for e in meta if e.get("name") in wanted] |
| missing = wanted - {e.get("name") for e in entries} |
| if missing: |
| print(f"[warn] entries not found: {sorted(missing)}", file=sys.stderr) |
| else: |
| entries = list(meta) |
|
|
| if args.indices is not None: |
| bad = [i for i in args.indices if i < 0 or i >= len(entries)] |
| if bad: |
| raise SystemExit( |
| f"--indices out of range {bad} (have {len(entries)} entries)" |
| ) |
| entries = [entries[i] for i in args.indices] |
|
|
| if args.limit is not None: |
| entries = entries[: args.limit] |
|
|
| out_root = Path(args.output_root) |
| out_root.mkdir(parents=True, exist_ok=True) |
|
|
| print(f"[boot] {len(entries)} cases → {out_root} (visibility={args.visibility})") |
|
|
| n_ok, n_fail = 0, 0 |
| for entry in entries: |
| try: |
| convert_case( |
| entry, out_root, |
| target_w=args.target_w, target_h=args.target_h, |
| num_frames=args.num_frames, |
| viz_num_frames=args.viz_num_frames, |
| points_per_voxel=args.points_per_voxel, |
| dyn_samples_per_voxel=args.dyn_samples_per_voxel, |
| voxel_size_scale=args.voxel_size_scale, |
| visibility=args.visibility, |
| depth_views=args.depth_views, |
| z_tol_rel=args.z_tol_rel, |
| z_tol_abs=args.z_tol_abs, |
| final_voxel_downsample=args.final_voxel_downsample, |
| fg_dilate=args.fg_dilate, |
| seed=args.seed, |
| overwrite=args.overwrite, |
| save_projection_videos=not args.no_projection_videos, |
| save_bg_projection_video=not args.no_bg_projection_video, |
| viz_fps=args.viz_fps, |
| viz_colormap=args.viz_colormap, |
| ) |
| n_ok += 1 |
| except Exception as e: |
| n_fail += 1 |
| print(f"[FAIL] {entry.get('name')}: {e}", file=sys.stderr) |
|
|
| print(f"\n[done] ok={n_ok}, fail={n_fail}, total={len(entries)}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|