| """Build ``points3d.ply`` from the first frame of every static camera. |
| |
| The camera metadata uses Blender camera coordinates: +X right, +Y up, and |
| +Z backward. Depth therefore projects along -Z before the camera-to-world |
| transform is applied. ``CineCamera_Moving`` is intentionally excluded. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| from pathlib import Path, PurePosixPath |
| import re |
| import tempfile |
|
|
| import numpy as np |
| from PIL import Image |
|
|
|
|
| STATIC_CAMERA_METADATA = re.compile(r"^blender_(CineCamera_\d+)\.json$") |
|
|
|
|
| def static_camera_metadata(render_dir: Path) -> list[Path]: |
| def camera_index(path: Path) -> int: |
| match = STATIC_CAMERA_METADATA.fullmatch(path.name) |
| if match is None: |
| return -1 |
| return int(match.group(1).removeprefix("CineCamera_")) |
|
|
| files = [ |
| path |
| for path in render_dir.glob("blender_CineCamera_*.json") |
| if STATIC_CAMERA_METADATA.fullmatch(path.name) |
| ] |
| return sorted(files, key=camera_index) |
|
|
|
|
| def first_frame_paths(render_dir: Path, frame: dict) -> tuple[Path, Path]: |
| raw_path = str(frame["file_path"]).replace("\\", "/") |
| relative = PurePosixPath(raw_path) |
| parts = list(relative.parts) |
| try: |
| rgb_index = parts.index("rgb") |
| except ValueError as exc: |
| raise ValueError(f"Camera frame path does not contain an rgb component: {raw_path}") from exc |
|
|
| rgb_relative = relative if relative.suffix.lower() == ".jpg" else relative.with_suffix(".jpg") |
| parts[rgb_index] = "depth" |
| depth_relative = PurePosixPath(*parts).with_suffix(".npz") |
| return render_dir.joinpath(*rgb_relative.parts), render_dir.joinpath(*depth_relative.parts) |
|
|
|
|
| def load_rgb(path: Path) -> np.ndarray: |
| with Image.open(path) as image: |
| rgb = np.asarray(image.convert("RGB")) |
| if rgb.ndim == 2: |
| rgb = np.repeat(rgb[..., None], 3, axis=-1) |
| if rgb.ndim != 3 or rgb.shape[2] < 3: |
| raise ValueError(f"Unsupported RGB image shape for {path}: {rgb.shape}") |
| rgb = rgb[..., :3] |
| if rgb.dtype != np.uint8: |
| if np.issubdtype(rgb.dtype, np.floating) and np.nanmax(rgb) <= 1.0: |
| rgb = rgb * 255.0 |
| rgb = np.clip(rgb, 0, 255).astype(np.uint8) |
| return rgb |
|
|
|
|
| def write_binary_ply(path: Path, points: np.ndarray, colors: np.ndarray) -> None: |
| path.parent.mkdir(parents=True, exist_ok=True) |
| vertex_type = np.dtype( |
| [ |
| ("x", "<f8"), |
| ("y", "<f8"), |
| ("z", "<f8"), |
| ("red", "u1"), |
| ("green", "u1"), |
| ("blue", "u1"), |
| ] |
| ) |
| vertices = np.empty(len(points), dtype=vertex_type) |
| vertices["x"], vertices["y"], vertices["z"] = points.T |
| vertices["red"], vertices["green"], vertices["blue"] = colors.T |
| header = ( |
| "ply\n" |
| "format binary_little_endian 1.0\n" |
| "comment Created by PhysInOne Camera and Rendering Tools\n" |
| f"element vertex {len(vertices)}\n" |
| "property double x\n" |
| "property double y\n" |
| "property double z\n" |
| "property uchar red\n" |
| "property uchar green\n" |
| "property uchar blue\n" |
| "end_header\n" |
| ).encode("ascii") |
|
|
| with tempfile.NamedTemporaryFile(dir=path.parent, suffix=".ply", delete=False) as handle: |
| temporary = Path(handle.name) |
| handle.write(header) |
| vertices.tofile(handle) |
| try: |
| if temporary.stat().st_size <= len(header): |
| raise RuntimeError(f"PLY writer produced no vertices: {temporary}") |
| temporary.chmod(0o664) |
| temporary.replace(path) |
| finally: |
| temporary.unlink(missing_ok=True) |
|
|
|
|
| def valid_ply(path: Path) -> bool: |
| if not path.is_file() or path.stat().st_size == 0: |
| return False |
| try: |
| with path.open("rb") as handle: |
| header = handle.read(2048).split(b"end_header\n", 1)[0].decode("ascii") |
| match = re.search(r"^element vertex (\d+)$", header, flags=re.MULTILINE) |
| return header.startswith("ply\n") and match is not None and int(match.group(1)) > 0 |
| except (OSError, UnicodeDecodeError, ValueError): |
| return False |
|
|
|
|
| def generate_points3d( |
| render_dir: Path, |
| output: Path | None = None, |
| depth_threshold: float = 20.0, |
| max_points: int = 100_000, |
| seed: int = 0, |
| ) -> dict[str, int | float | str]: |
| """Generate one point cloud using frame zero from every static view. |
| |
| Random priorities implement a bounded-memory uniform sample across all |
| valid pixels from all views. The seed makes the output reproducible. |
| """ |
|
|
| render_dir = render_dir.expanduser().resolve() |
| output = render_dir / "points3d.ply" if output is None else output.expanduser().resolve() |
| if depth_threshold <= 0: |
| raise ValueError("depth_threshold must be positive") |
| if max_points <= 0: |
| raise ValueError("max_points must be positive") |
|
|
| metadata_files = static_camera_metadata(render_dir) |
| if not metadata_files: |
| raise RuntimeError(f"No static blender_CineCamera_<index>.json files under {render_dir}") |
|
|
| rng = np.random.default_rng(seed) |
| kept_keys = np.empty(0, dtype=np.float64) |
| kept_points = np.empty((0, 3), dtype=np.float64) |
| kept_colors = np.empty((0, 3), dtype=np.uint8) |
| valid_pixels = 0 |
| used_views = 0 |
|
|
| for metadata_path in metadata_files: |
| with metadata_path.open("r", encoding="utf-8") as handle: |
| document = json.load(handle) |
| frames = document.get("frames", []) |
| if not frames: |
| raise RuntimeError(f"Camera metadata has no frames: {metadata_path}") |
|
|
| frame = frames[0] |
| rgb_path, depth_path = first_frame_paths(render_dir, frame) |
| if not rgb_path.is_file() or not depth_path.is_file(): |
| raise FileNotFoundError( |
| f"Missing first-frame input for {metadata_path.name}: rgb={rgb_path}, depth={depth_path}" |
| ) |
|
|
| with np.load(depth_path) as depth_file: |
| if "depth" not in depth_file: |
| raise KeyError(f"Missing 'depth' array in {depth_path}") |
| depth = np.asarray(depth_file["depth"], dtype=np.float64) |
| rgb = load_rgb(rgb_path) |
| if depth.ndim != 2 or rgb.shape[:2] != depth.shape: |
| raise ValueError( |
| f"RGB/depth shape mismatch for {metadata_path.name}: rgb={rgb.shape}, depth={depth.shape}" |
| ) |
|
|
| height, width = depth.shape |
| image_width = int(document.get("img_w", width)) |
| image_height = int(document.get("img_h", height)) |
| if (image_height, image_width) != (height, width): |
| raise ValueError( |
| f"Metadata/image shape mismatch for {metadata_path.name}: " |
| f"metadata={(image_height, image_width)}, image={(height, width)}" |
| ) |
| camera_angle_x = float(document["camera_angle_x"]) |
| focal = 0.5 * image_width / np.tan(0.5 * camera_angle_x) |
| transform = np.asarray(frame["transform_matrix"], dtype=np.float64) |
| if transform.shape != (4, 4): |
| raise ValueError(f"Expected a 4x4 transform matrix in {metadata_path}") |
|
|
| valid = np.isfinite(depth) & (depth > 0.0) & (depth < depth_threshold) |
| flat_indices = np.flatnonzero(valid) |
| if flat_indices.size == 0: |
| raise RuntimeError(f"No valid first-frame depth pixels in {metadata_path.name}") |
| valid_pixels += int(flat_indices.size) |
| used_views += 1 |
|
|
| priorities = rng.random(flat_indices.size) |
| if flat_indices.size > max_points: |
| selected = np.argpartition(priorities, max_points - 1)[:max_points] |
| flat_indices = flat_indices[selected] |
| priorities = priorities[selected] |
|
|
| rows, columns = np.divmod(flat_indices, width) |
| z = depth.reshape(-1)[flat_indices] |
| camera_points = np.column_stack( |
| ( |
| (columns - image_width / 2.0) * z / focal, |
| -(rows - image_height / 2.0) * z / focal, |
| -z, |
| ) |
| ) |
| world_points = camera_points @ transform[:3, :3].T + transform[:3, 3] |
| colors = rgb.reshape(-1, 3)[flat_indices] |
|
|
| kept_keys = np.concatenate((kept_keys, priorities)) |
| kept_points = np.concatenate((kept_points, world_points), axis=0) |
| kept_colors = np.concatenate((kept_colors, colors), axis=0) |
| if kept_keys.size > max_points: |
| selected = np.argpartition(kept_keys, max_points - 1)[:max_points] |
| kept_keys = kept_keys[selected] |
| kept_points = kept_points[selected] |
| kept_colors = kept_colors[selected] |
|
|
| if used_views != len(metadata_files): |
| raise RuntimeError(f"Used {used_views}/{len(metadata_files)} static views") |
| write_binary_ply(output, kept_points, kept_colors) |
| if not valid_ply(output): |
| raise RuntimeError(f"Generated PLY did not pass validation: {output}") |
| return { |
| "views": used_views, |
| "valid_pixels": valid_pixels, |
| "points": int(len(kept_points)), |
| "depth_threshold": depth_threshold, |
| "output": str(output), |
| } |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser(description=__doc__) |
| parser.add_argument("render_dir", type=Path) |
| parser.add_argument("--output", type=Path, default=None) |
| parser.add_argument("--depth-threshold", type=float, default=20.0) |
| parser.add_argument("--max-points", type=int, default=100_000) |
| parser.add_argument("--seed", type=int, default=0) |
| return parser.parse_args() |
|
|
|
|
| def main() -> int: |
| args = parse_args() |
| result = generate_points3d( |
| args.render_dir, |
| args.output, |
| args.depth_threshold, |
| args.max_points, |
| args.seed, |
| ) |
| print(json.dumps(result, indent=2, sort_keys=True)) |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| raise SystemExit(main()) |
|
|