Download OVOW/benchmark/scripts/extract_scene_camera_depth.py from AIGeeksGroup/PhysicalWM: direct link, hf CLI and curl.
- Browser
- Download file 5.08 kB
-
https://huggingface.co/datasets/AIGeeksGroup/PhysicalWM/resolve/main/OVOW/benchmark/scripts/extract_scene_camera_depth.py
- Command line
-
hf download hf://datasets/AIGeeksGroup/PhysicalWM/OVOW/benchmark/scripts/extract_scene_camera_depth.py
-
curl -L -o extract_scene_camera_depth.py https://huggingface.co/datasets/AIGeeksGroup/PhysicalWM/resolve/main/OVOW/benchmark/scripts/extract_scene_camera_depth.py
5.08 kB
| 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() | |