File size: 4,807 Bytes
6da4e64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()