File size: 5,079 Bytes
cb8518a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

import bpy
import numpy as np


def parse_args() -> argparse.Namespace:
    argv_source = getattr(bpy.app, "argv", None)
    if argv_source is None:
        argv_source = sys.argv
    argv: list[str] = []
    if "--" in argv_source:
        argv = argv_source[argv_source.index("--") + 1 :]

    parser = argparse.ArgumentParser(description="Extract camera pose and approximate depth from a scene")
    parser.add_argument("--input", required=True, help="Input .blend/.glb/.gltf scene")
    parser.add_argument("--output_dir", required=True, help="Output directory for camera.json and depth.npy")
    parser.add_argument("--frame", type=int, default=None, help="Frame to evaluate; default scene.frame_start")
    parser.add_argument("--max_depth_samples", type=int, default=300000)
    parser.add_argument("--seed", type=int, default=42)
    return parser.parse_args(argv)


def load_input_scene(input_path: str) -> Path:
    path = Path(input_path).resolve()
    if not path.exists():
        raise FileNotFoundError(f"Input scene does not exist: {path}")

    ext = path.suffix.lower()
    if ext == ".blend":
        bpy.ops.wm.open_mainfile(filepath=str(path))
    elif ext in {".glb", ".gltf"}:
        bpy.ops.object.select_all(action="SELECT")
        bpy.ops.object.delete()
        bpy.ops.import_scene.gltf(filepath=str(path))
    else:
        raise ValueError(f"Unsupported input scene extension: {path.suffix}")
    return path


def pick_camera(scene: bpy.types.Scene) -> bpy.types.Object:
    if scene.camera is not None:
        return scene.camera
    cameras = [obj for obj in scene.objects if obj.type == "CAMERA"]
    if not cameras:
        raise FileNotFoundError("Scene has no camera; cannot auto-extract camera/depth metadata.")
    return cameras[0]


def world_vertices(obj_eval: bpy.types.Object, mesh: bpy.types.Mesh) -> np.ndarray:
    local = np.empty(len(mesh.vertices) * 3, dtype=np.float32)
    mesh.vertices.foreach_get("co", local)
    local = local.reshape(-1, 3)

    mat = np.array(obj_eval.matrix_world, dtype=np.float32)
    rot = mat[:3, :3]
    trans = mat[:3, 3]
    return (local @ rot.T + trans).astype(np.float32, copy=False)


def collect_depths(scene: bpy.types.Scene, camera: bpy.types.Object, max_samples: int, seed: int) -> np.ndarray:
    depsgraph = bpy.context.evaluated_depsgraph_get()
    w2c = np.array(camera.matrix_world.inverted(), dtype=np.float64)
    depths: list[np.ndarray] = []

    for obj in scene.objects:
        if obj.type != "MESH" or obj.hide_render:
            continue

        obj_eval = obj.evaluated_get(depsgraph)
        mesh = obj_eval.to_mesh(preserve_all_data_layers=False, depsgraph=depsgraph)
        if mesh is None:
            continue
        try:
            if len(mesh.vertices) == 0:
                continue
            verts = world_vertices(obj_eval, mesh).astype(np.float64)
            cam = verts @ w2c[:3, :3].T + w2c[:3, 3]

            depth = -cam[:, 2]
            depth = depth[np.isfinite(depth) & (depth > 1e-8)]
            if depth.size:
                depths.append(depth.astype(np.float32, copy=False))
        finally:
            obj_eval.to_mesh_clear()

    if not depths:
        return np.zeros((0,), dtype=np.float32)

    values = np.concatenate(depths, axis=0)
    if max_samples > 0 and values.size > max_samples:
        rng = np.random.default_rng(seed)
        idx = rng.choice(values.size, size=max_samples, replace=False)
        values = values[idx]
    return values.astype(np.float32, copy=False)


def main() -> None:
    args = parse_args()
    scene_path = load_input_scene(args.input)
    scene = bpy.context.scene
    frame = int(args.frame) if args.frame is not None else int(scene.frame_start)
    scene.frame_set(frame)

    camera = pick_camera(scene)
    camera_to_world = np.array(camera.matrix_world, dtype=np.float64)
    world_to_camera = np.array(camera.matrix_world.inverted(), dtype=np.float64)
    depths = collect_depths(scene, camera, args.max_depth_samples, args.seed)

    output_dir = Path(args.output_dir).resolve()
    output_dir.mkdir(parents=True, exist_ok=True)
    depth_path = output_dir / "depth.npy"
    camera_path = output_dir / "camera.json"
    np.save(depth_path, depths)

    payload = {
        "scene": str(scene_path),
        "frame": frame,
        "camera_name": camera.name,
        "world_to_camera": world_to_camera.tolist(),
        "camera_to_world": camera_to_world.tolist(),
        "depth_path": str(depth_path),
        "depth_count": int(depths.size),
        "depth_median": float(np.median(depths)) if depths.size else None,
        "depth_definition": "positive mesh vertex depth in Blender camera coordinates, depth=-z_camera",
    }
    camera_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    print(json.dumps({"camera": str(camera_path), "depth": str(depth_path), "depth_count": int(depths.size)}))


if __name__ == "__main__":
    main()