Download projects/spatial-0/scripts/export_nerfstudio.py from KineJIng/kinejing-open-source: direct link, hf CLI and curl.
- Browser
- Download file 4.81 kB
-
https://huggingface.co/datasets/KineJIng/kinejing-open-source/resolve/main/projects/spatial-0/scripts/export_nerfstudio.py
- Command line
-
hf download hf://datasets/KineJIng/kinejing-open-source/projects/spatial-0/scripts/export_nerfstudio.py
-
curl -L -o export_nerfstudio.py https://huggingface.co/datasets/KineJIng/kinejing-open-source/resolve/main/projects/spatial-0/scripts/export_nerfstudio.py
4.81 kB
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| from PIL import Image | |
| from plyfile import PlyData, PlyElement | |
| def homogeneous(extrinsic: np.ndarray) -> np.ndarray: | |
| matrix = np.eye(4, dtype=np.float64) | |
| matrix[:3, :4] = extrinsic | |
| return matrix | |
| def build_initial_points(data, confidence_percentile: float, maximum_points: int): | |
| images, depth, confidence = data["image"], data["depth"], data["conf"] | |
| intrinsics, extrinsics = data["intrinsics"], data["extrinsics"] | |
| frame_count, height, width = depth.shape | |
| u, v = np.meshgrid(np.arange(width), np.arange(height)) | |
| pixels = np.stack([u, v, np.ones_like(u)], axis=-1).reshape(-1, 3) | |
| threshold = np.percentile(confidence, confidence_percentile) | |
| points, colors = [], [] | |
| for index in range(frame_count): | |
| valid = np.isfinite(depth[index]) & (depth[index] > 0) & (confidence[index] >= threshold) | |
| selected = np.flatnonzero(valid.reshape(-1)) | |
| rays = np.linalg.inv(intrinsics[index]) @ pixels[selected].T | |
| camera_points = rays * depth[index].reshape(-1)[selected][None] | |
| camera_points = np.vstack([camera_points, np.ones((1, camera_points.shape[1]))]) | |
| camera_to_world = np.linalg.inv(homogeneous(extrinsics[index])) | |
| points.append((camera_to_world @ camera_points)[:3].T.astype(np.float32)) | |
| colors.append(images[index].reshape(-1, 3)[selected].astype(np.uint8)) | |
| points, colors = np.concatenate(points), np.concatenate(colors) | |
| finite = np.isfinite(points).all(axis=1) | |
| points, colors = points[finite], colors[finite] | |
| if len(points) > maximum_points: | |
| selected = np.random.default_rng(0).choice(len(points), maximum_points, replace=False) | |
| points, colors = points[selected], colors[selected] | |
| return points, colors, float(threshold) | |
| def write_ply(path: Path, points: np.ndarray, colors: np.ndarray) -> None: | |
| vertex = np.empty(len(points), dtype=[ | |
| ("x", "f4"), ("y", "f4"), ("z", "f4"), | |
| ("red", "u1"), ("green", "u1"), ("blue", "u1"), | |
| ]) | |
| vertex["x"], vertex["y"], vertex["z"] = points.T | |
| vertex["red"], vertex["green"], vertex["blue"] = colors.T | |
| PlyData([PlyElement.describe(vertex, "vertex")], text=False).write(path) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description="Export Spatial-0 output as a Nerfstudio dataset") | |
| parser.add_argument("npz", type=Path) | |
| parser.add_argument("output", type=Path) | |
| parser.add_argument("--confidence-percentile", type=float, default=40.0) | |
| parser.add_argument("--maximum-points", type=int, default=300_000) | |
| args = parser.parse_args() | |
| output = args.output.resolve() | |
| images_dir = output / "images" | |
| images_dir.mkdir(parents=True, exist_ok=True) | |
| data = np.load(args.npz.resolve()) | |
| images = data["image"] | |
| intrinsics, extrinsics = data["intrinsics"], data["extrinsics"] | |
| height, width = images.shape[1:3] | |
| opencv_to_opengl = np.diag([1.0, -1.0, -1.0, 1.0]) | |
| frames = [] | |
| provenance = data["provenance"].tolist() if "provenance" in data else ["frame"]*len(images) | |
| if len(provenance) != len(images) or any(p not in {"frame", "observed", "generated"} for p in provenance): | |
| raise ValueError("Invalid per-frame provenance") | |
| for index, image in enumerate(images): | |
| name = f"{provenance[index]}-{index + 1:04d}.png" | |
| Image.fromarray(image).save(images_dir / name) | |
| camera_to_world = np.linalg.inv(homogeneous(extrinsics[index])) @ opencv_to_opengl | |
| frames.append({ | |
| "file_path": f"images/{name}", | |
| "fl_x": float(intrinsics[index, 0, 0]), | |
| "fl_y": float(intrinsics[index, 1, 1]), | |
| "cx": float(intrinsics[index, 0, 2]), | |
| "cy": float(intrinsics[index, 1, 2]), | |
| "w": width, | |
| "h": height, | |
| "transform_matrix": camera_to_world.tolist(), | |
| }) | |
| points, colors, threshold = build_initial_points( | |
| data, args.confidence_percentile, args.maximum_points | |
| ) | |
| write_ply(output / "sparse_pc.ply", points, colors) | |
| transforms = { | |
| "camera_model": "OPENCV", | |
| "k1": 0.0, | |
| "k2": 0.0, | |
| "p1": 0.0, | |
| "p2": 0.0, | |
| "ply_file_path": "sparse_pc.ply", | |
| "frames": frames, | |
| "spatial0": { | |
| "source": str(args.npz.name), | |
| "confidence_percentile": args.confidence_percentile, | |
| "confidence_threshold": threshold, | |
| "initial_points": len(points), | |
| "scale": "model-relative; not metric calibrated", | |
| }, | |
| } | |
| (output / "transforms.json").write_text(json.dumps(transforms, indent=2), encoding="utf-8") | |
| print(json.dumps(transforms["spatial0"], indent=2)) | |
| if __name__ == "__main__": | |
| main() | |