Download OVOW/benchmark/scripts/render_aligned_eval_images.py from AIGeeksGroup/PhysicalWM: direct link, hf CLI and curl.
- Browser
- Download file 12 kB
-
https://huggingface.co/datasets/AIGeeksGroup/PhysicalWM/resolve/main/OVOW/benchmark/scripts/render_aligned_eval_images.py
- Command line
-
hf download hf://datasets/AIGeeksGroup/PhysicalWM/OVOW/benchmark/scripts/render_aligned_eval_images.py
-
curl -L -o render_aligned_eval_images.py https://huggingface.co/datasets/AIGeeksGroup/PhysicalWM/resolve/main/OVOW/benchmark/scripts/render_aligned_eval_images.py
12 kB
| #!/usr/bin/env python3 | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import sys | |
| from pathlib import Path | |
| from typing import Any, Iterable | |
| import bpy | |
| from mathutils import Matrix, Vector | |
| OBJECT_TYPES = {"MESH", "EMPTY", "ARMATURE", "CURVE", "SURFACE", "FONT"} | |
| def parse_args() -> argparse.Namespace: | |
| argv_source = getattr(bpy.app, "argv", None) or sys.argv | |
| argv: list[str] = [] | |
| if "--" in argv_source: | |
| argv = argv_source[argv_source.index("--") + 1 :] | |
| parser = argparse.ArgumentParser(description="Render aligned eval images from a run_big_eval report") | |
| parser.add_argument("--report_json", required=True) | |
| parser.add_argument("--out_dir", required=True) | |
| parser.add_argument("--models", default=None, help="Comma-separated model keys; defaults to report order.") | |
| parser.add_argument("--render_gt", action=argparse.BooleanOptionalAction, default=True) | |
| parser.add_argument("--resolution_x", type=int, default=768) | |
| parser.add_argument("--resolution_y", type=int, default=432) | |
| parser.add_argument("--samples", type=int, default=32) | |
| parser.add_argument("--engine", choices=["BLENDER_EEVEE", "BLENDER_EEVEE_NEXT", "CYCLES"], default="BLENDER_EEVEE") | |
| parser.add_argument("--transparent", action=argparse.BooleanOptionalAction, default=False) | |
| return parser.parse_args(argv) | |
| def clear_scene() -> None: | |
| bpy.ops.object.select_all(action="SELECT") | |
| bpy.ops.object.delete() | |
| for collection in list(bpy.data.collections): | |
| bpy.data.collections.remove(collection) | |
| for block in ( | |
| bpy.data.meshes, | |
| bpy.data.materials, | |
| bpy.data.images, | |
| bpy.data.lights, | |
| bpy.data.cameras, | |
| bpy.data.curves, | |
| bpy.data.armatures, | |
| ): | |
| for item in list(block): | |
| if item.users == 0: | |
| block.remove(item) | |
| def load_scene(path: Path) -> None: | |
| ext = path.suffix.lower() | |
| if ext == ".blend": | |
| bpy.ops.wm.open_mainfile(filepath=str(path)) | |
| return | |
| clear_scene() | |
| if ext in {".glb", ".gltf"}: | |
| bpy.ops.import_scene.gltf(filepath=str(path)) | |
| return | |
| raise ValueError(f"Unsupported scene asset: {path}") | |
| def active_camera() -> bpy.types.Object: | |
| scene = bpy.context.scene | |
| if scene.camera is not None and scene.camera.type == "CAMERA": | |
| return scene.camera | |
| cameras = [obj for obj in scene.objects if obj.type == "CAMERA"] | |
| if not cameras: | |
| raise FileNotFoundError("GT scene has no camera to copy for rendering.") | |
| return cameras[0] | |
| def copy_camera_data(src: bpy.types.Camera) -> bpy.types.Camera: | |
| dst = bpy.data.cameras.new("Eval_GT_Camera_Data") | |
| dst.type = src.type | |
| dst.lens = src.lens | |
| dst.sensor_width = src.sensor_width | |
| dst.sensor_height = src.sensor_height | |
| dst.sensor_fit = src.sensor_fit | |
| dst.shift_x = src.shift_x | |
| dst.shift_y = src.shift_y | |
| dst.clip_start = src.clip_start | |
| dst.clip_end = src.clip_end | |
| dst.ortho_scale = src.ortho_scale | |
| dst.dof.use_dof = False | |
| return dst | |
| def baked_gt_camera(gt_scene: Path, gt_matrix: list[list[float]], gt_frame: int) -> dict[str, Any]: | |
| load_scene(gt_scene) | |
| scene = bpy.context.scene | |
| scene.frame_set(gt_frame) | |
| bpy.context.view_layer.update() | |
| cam = active_camera() | |
| eval_matrix = Matrix(gt_matrix) @ cam.matrix_world.copy() | |
| return { | |
| "matrix_world": [[float(v) for v in row] for row in eval_matrix], | |
| "data": { | |
| "type": cam.data.type, | |
| "lens": float(cam.data.lens), | |
| "sensor_width": float(cam.data.sensor_width), | |
| "sensor_height": float(cam.data.sensor_height), | |
| "sensor_fit": cam.data.sensor_fit, | |
| "shift_x": float(cam.data.shift_x), | |
| "shift_y": float(cam.data.shift_y), | |
| "clip_start": float(cam.data.clip_start), | |
| "clip_end": float(cam.data.clip_end), | |
| "ortho_scale": float(cam.data.ortho_scale), | |
| }, | |
| } | |
| def add_baked_camera(camera_info: dict[str, Any]) -> bpy.types.Object: | |
| data_info = camera_info["data"] | |
| cam_data = bpy.data.cameras.new("Eval_GT_Camera_Data") | |
| cam_data.type = data_info["type"] | |
| cam_data.lens = data_info["lens"] | |
| cam_data.sensor_width = data_info["sensor_width"] | |
| cam_data.sensor_height = data_info["sensor_height"] | |
| cam_data.sensor_fit = data_info["sensor_fit"] | |
| cam_data.shift_x = data_info["shift_x"] | |
| cam_data.shift_y = data_info["shift_y"] | |
| cam_data.clip_start = data_info["clip_start"] | |
| cam_data.clip_end = max(data_info["clip_end"], 1000.0) | |
| cam_data.ortho_scale = data_info["ortho_scale"] | |
| cam = bpy.data.objects.new("Eval_GT_Camera", cam_data) | |
| bpy.context.scene.collection.objects.link(cam) | |
| cam.matrix_world = Matrix(camera_info["matrix_world"]) | |
| bpy.context.scene.camera = cam | |
| return cam | |
| def root_objects(objects: Iterable[bpy.types.Object]) -> list[bpy.types.Object]: | |
| object_set = set(objects) | |
| return [obj for obj in objects if obj.parent not in object_set] | |
| def remove_cameras_and_lights() -> None: | |
| for obj in list(bpy.context.scene.objects): | |
| if obj.type in {"CAMERA", "LIGHT"}: | |
| bpy.data.objects.remove(obj, do_unlink=True) | |
| def apply_alignment(matrix: list[list[float]]) -> None: | |
| objects = [obj for obj in bpy.context.scene.objects if obj.type in OBJECT_TYPES] | |
| parent = bpy.data.objects.new("Eval_Alignment", None) | |
| bpy.context.scene.collection.objects.link(parent) | |
| parent.matrix_world = Matrix(matrix) | |
| for obj in root_objects(objects): | |
| obj.parent = parent | |
| obj.matrix_parent_inverse = Matrix.Identity(4) | |
| def scene_bounds() -> tuple[Vector, Vector] | None: | |
| bpy.context.view_layer.update() | |
| mins: list[Vector] = [] | |
| maxs: list[Vector] = [] | |
| for obj in bpy.context.scene.objects: | |
| if obj.type != "MESH": | |
| continue | |
| corners = [obj.matrix_world @ Vector(corner) for corner in obj.bound_box] | |
| mins.append(Vector((min(v.x for v in corners), min(v.y for v in corners), min(v.z for v in corners)))) | |
| maxs.append(Vector((max(v.x for v in corners), max(v.y for v in corners), max(v.z for v in corners)))) | |
| if not mins: | |
| return None | |
| return ( | |
| Vector((min(v.x for v in mins), min(v.y for v in mins), min(v.z for v in mins))), | |
| Vector((max(v.x for v in maxs), max(v.y for v in maxs), max(v.z for v in maxs))), | |
| ) | |
| def add_eval_light() -> None: | |
| bounds = scene_bounds() | |
| if bounds is None: | |
| loc = Vector((3.0, -4.0, 5.0)) | |
| size = 4.0 | |
| energy = 450.0 | |
| else: | |
| bmin, bmax = bounds | |
| center = 0.5 * (bmin + bmax) | |
| diag = max((bmax - bmin).length, 1.0) | |
| loc = center + Vector((0.35 * diag, -0.65 * diag, 1.1 * diag)) | |
| size = max(3.0, 0.55 * diag) | |
| energy = 500.0 | |
| light_data = bpy.data.lights.new("Eval_Key_Light", "AREA") | |
| light = bpy.data.objects.new("Eval_Key_Light", light_data) | |
| bpy.context.scene.collection.objects.link(light) | |
| light.location = loc | |
| light.data.size = size | |
| light.data.energy = energy | |
| def configure_render(args: argparse.Namespace, output: Path) -> None: | |
| scene = bpy.context.scene | |
| engine = args.engine | |
| try: | |
| scene.render.engine = engine | |
| except TypeError: | |
| if engine in {"BLENDER_EEVEE", "BLENDER_EEVEE_NEXT"}: | |
| fallback = "BLENDER_EEVEE_NEXT" if engine == "BLENDER_EEVEE" else "BLENDER_EEVEE" | |
| scene.render.engine = fallback | |
| engine = fallback | |
| else: | |
| raise | |
| if engine == "CYCLES": | |
| scene.cycles.samples = args.samples | |
| elif hasattr(scene, "eevee"): | |
| scene.eevee.taa_render_samples = args.samples | |
| scene.render.resolution_x = args.resolution_x | |
| scene.render.resolution_y = args.resolution_y | |
| scene.render.resolution_percentage = 100 | |
| scene.render.film_transparent = bool(args.transparent) | |
| scene.render.image_settings.file_format = "PNG" | |
| scene.render.filepath = str(output) | |
| scene.view_settings.view_transform = "Filmic" | |
| scene.view_settings.look = "Medium High Contrast" | |
| scene.view_settings.exposure = 0.0 | |
| scene.view_settings.gamma = 1.0 | |
| scene.world.color = (0.04, 0.04, 0.04) | |
| def frame_pairs_for(report: dict[str, Any], key: str) -> list[tuple[int, int]]: | |
| details = report.get("iou_b", {}).get(key, {}).get("frame_details", []) | |
| pairs: list[tuple[int, int]] = [] | |
| for item in details: | |
| if "gt_frame_no" in item and "pred_frame_no" in item: | |
| pairs.append((int(item["gt_frame_no"]), int(item["pred_frame_no"]))) | |
| if pairs: | |
| return pairs | |
| return [(1, 1)] | |
| def default_models(report: dict[str, Any]) -> list[str]: | |
| keys = [row["model"] for row in report.get("summary", []) if row.get("model") in report.get("alignments", {})] | |
| if keys: | |
| return keys | |
| return [key for key in report.get("alignments", {}) if key != "gt"] | |
| def render_one( | |
| *, | |
| args: argparse.Namespace, | |
| key: str, | |
| scene_path: Path, | |
| matrix: list[list[float]], | |
| camera_info: dict[str, Any], | |
| target_frame: int, | |
| output: Path, | |
| ) -> None: | |
| load_scene(scene_path) | |
| bpy.context.scene.frame_set(target_frame) | |
| bpy.context.view_layer.update() | |
| remove_cameras_and_lights() | |
| apply_alignment(matrix) | |
| add_baked_camera(camera_info) | |
| add_eval_light() | |
| output.parent.mkdir(parents=True, exist_ok=True) | |
| configure_render(args, output) | |
| bpy.ops.render.render(write_still=True) | |
| print(f"RENDERED key={key} frame={target_frame} output={output}") | |
| def main() -> None: | |
| args = parse_args() | |
| report_path = Path(args.report_json).resolve() | |
| report = json.loads(report_path.read_text(encoding="utf-8")) | |
| out_dir = Path(args.out_dir).resolve() | |
| model_keys = [x.strip() for x in args.models.split(",") if x.strip()] if args.models else default_models(report) | |
| gt_scene = Path(report["paths"]["gt"]["scene"]) | |
| first_key = model_keys[0] | |
| gt_matrix = report["alignments"][first_key]["gt_matrix"] | |
| manifest: dict[str, Any] = { | |
| "report_json": str(report_path), | |
| "gt_scene": str(gt_scene), | |
| "models": model_keys, | |
| "renders": {}, | |
| } | |
| if args.render_gt: | |
| gt_pairs = frame_pairs_for(report, first_key) | |
| manifest["renders"]["gt"] = [] | |
| for idx, (gt_frame, _) in enumerate(gt_pairs): | |
| camera_info = baked_gt_camera(gt_scene, gt_matrix, gt_frame) | |
| output = out_dir / "gt" / f"frame_{idx:03d}_gt{gt_frame:04d}.png" | |
| render_one( | |
| args=args, | |
| key="gt", | |
| scene_path=gt_scene, | |
| matrix=gt_matrix, | |
| camera_info=camera_info, | |
| target_frame=gt_frame, | |
| output=output, | |
| ) | |
| manifest["renders"]["gt"].append({"gt_frame": gt_frame, "pred_frame": gt_frame, "path": str(output)}) | |
| for key in model_keys: | |
| pred_scene = Path(report["paths"][key]["scene"]) | |
| pred_matrix = report["alignments"][key]["pred_matrix"] | |
| pairs = frame_pairs_for(report, key) | |
| manifest["renders"][key] = [] | |
| for idx, (gt_frame, pred_frame) in enumerate(pairs): | |
| camera_info = baked_gt_camera(gt_scene, gt_matrix, gt_frame) | |
| output = out_dir / key / f"frame_{idx:03d}_gt{gt_frame:04d}_pred{pred_frame:04d}.png" | |
| render_one( | |
| args=args, | |
| key=key, | |
| scene_path=pred_scene, | |
| matrix=pred_matrix, | |
| camera_info=camera_info, | |
| target_frame=pred_frame, | |
| output=output, | |
| ) | |
| manifest["renders"][key].append({"gt_frame": gt_frame, "pred_frame": pred_frame, "path": str(output)}) | |
| manifest_path = out_dir / "render_manifest.json" | |
| manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") | |
| print(f"WROTE_MANIFEST {manifest_path}") | |
| if __name__ == "__main__": | |
| main() | |