Download Utils/data_processing/postprocess/exr_to_dataset.py from vLAR/PhysInOne: direct link, hf CLI and curl.
- Browser
- Download file 10 kB
-
https://huggingface.co/datasets/vLAR/PhysInOne/resolve/main/Utils/data_processing/postprocess/exr_to_dataset.py
- Command line
-
hf download hf://datasets/vLAR/PhysInOne/Utils/data_processing/postprocess/exr_to_dataset.py
-
curl -L -o exr_to_dataset.py https://huggingface.co/datasets/vLAR/PhysInOne/resolve/main/Utils/data_processing/postprocess/exr_to_dataset.py
10 kB
| """Convert Unreal Movie Render Queue EXRs into PhysInOne dataset files. | |
| RGB passes become JPEG files. World-depth and custom-stencil passes become | |
| compressed NPZ files with keys ``depth`` and ``seg``. By default it also | |
| builds ``points3d.ply`` from the first frame of every static camera. This tool | |
| never samples views and never creates or modifies transforms_train/val/test.json. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| from dataclasses import dataclass | |
| import json | |
| from pathlib import Path | |
| import re | |
| import shutil | |
| import sys | |
| import tempfile | |
| import imageio.v2 as imageio | |
| import Imath | |
| import numpy as np | |
| import OpenEXR | |
| PACKAGE_ROOT = Path(__file__).resolve().parent.parent | |
| if str(PACKAGE_ROOT) not in sys.path: | |
| sys.path.insert(0, str(PACKAGE_ROOT)) | |
| from postprocess.point_cloud import generate_points3d | |
| try: | |
| from tqdm import tqdm | |
| except ImportError: # pragma: no cover | |
| def tqdm(iterable=None, **_kwargs): | |
| return iterable if iterable is not None else () | |
| PASS_PATTERNS = { | |
| "depth": re.compile( | |
| r"(?:FinalImage|PathTracer)MovieRenderQueue_WorldDepth_meter\.(\d+)\.exr$", | |
| re.IGNORECASE, | |
| ), | |
| "seg": re.compile( | |
| r"(?:FinalImage|PathTracer)CustomStencil_woText\.(\d+)\.exr$", | |
| re.IGNORECASE, | |
| ), | |
| "rgb": re.compile(r"(?:FinalImage|PathTracer)\.(\d+)\.exr$", re.IGNORECASE), | |
| } | |
| class Job: | |
| source: Path | |
| destination: Path | |
| channel: str | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("render_dirs", nargs="+", type=Path) | |
| parser.add_argument( | |
| "--output-dir", | |
| type=Path, | |
| default=None, | |
| help="Optional destination for one input directory. Default: convert in place.", | |
| ) | |
| parser.add_argument("--workers", type=int, default=8) | |
| parser.add_argument("--jpeg-quality", type=int, default=95) | |
| parser.add_argument( | |
| "--channels", | |
| default="rgb,depth,seg", | |
| help="Comma-separated subset of rgb,depth,seg.", | |
| ) | |
| parser.add_argument( | |
| "--delete-source-exr", | |
| action="store_true", | |
| help="Delete each EXR only after its converted output passes validation.", | |
| ) | |
| parser.add_argument( | |
| "--skip-ply", | |
| action="store_true", | |
| help="Do not generate points3d.ply after conversion.", | |
| ) | |
| parser.add_argument( | |
| "--depth-threshold", | |
| type=float, | |
| default=20.0, | |
| help="Maximum valid depth in meters for points3d.ply (default: 20).", | |
| ) | |
| parser.add_argument( | |
| "--max-points", | |
| type=int, | |
| default=100_000, | |
| help="Maximum number of vertices in points3d.ply (default: 100000).", | |
| ) | |
| parser.add_argument("--ply-seed", type=int, default=0) | |
| return parser.parse_args() | |
| def classify(path: Path) -> tuple[str, int] | None: | |
| for channel in ("depth", "seg", "rgb"): | |
| match = PASS_PATTERNS[channel].search(path.name) | |
| if match: | |
| return channel, int(match.group(1)) | |
| return None | |
| def read_exr(path: Path, channels: tuple[str, ...]) -> np.ndarray: | |
| exr = OpenEXR.InputFile(str(path)) | |
| try: | |
| window = exr.header()["dataWindow"] | |
| width = window.max.x - window.min.x + 1 | |
| height = window.max.y - window.min.y + 1 | |
| pixel_type = Imath.PixelType(Imath.PixelType.FLOAT) | |
| arrays = [ | |
| np.frombuffer(exr.channel(channel, pixel_type), dtype=np.float32).reshape(height, width) | |
| for channel in channels | |
| ] | |
| return arrays[0] if len(arrays) == 1 else np.stack(arrays, axis=-1) | |
| finally: | |
| exr.close() | |
| def atomic_jpeg(path: Path, rgb: np.ndarray, quality: int) -> None: | |
| mapped = np.power(np.clip(rgb, 0.0, 1.0), 1.0 / 2.2) | |
| image = np.rint(mapped * 255.0).astype(np.uint8) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with tempfile.NamedTemporaryFile(dir=path.parent, suffix=".jpg", delete=False) as handle: | |
| temporary = Path(handle.name) | |
| try: | |
| imageio.imwrite(temporary, image, quality=quality) | |
| if temporary.stat().st_size == 0: | |
| raise RuntimeError("JPEG writer produced an empty file.") | |
| temporary.replace(path) | |
| finally: | |
| temporary.unlink(missing_ok=True) | |
| def atomic_npz(path: Path, key: str, array: np.ndarray) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with tempfile.NamedTemporaryFile(dir=path.parent, suffix=".npz", delete=False) as handle: | |
| temporary = Path(handle.name) | |
| np.savez_compressed(handle, **{key: array}) | |
| try: | |
| with np.load(temporary) as data: | |
| if key not in data or data[key].shape != array.shape: | |
| raise RuntimeError(f"NPZ verification failed for {temporary}") | |
| temporary.replace(path) | |
| finally: | |
| temporary.unlink(missing_ok=True) | |
| def convert(job: Job, jpeg_quality: int, delete_source: bool) -> tuple[str, Path]: | |
| if job.channel == "rgb": | |
| atomic_jpeg(job.destination, read_exr(job.source, ("R", "G", "B")), jpeg_quality) | |
| elif job.channel == "depth": | |
| atomic_npz(job.destination, "depth", read_exr(job.source, ("R",))) | |
| else: | |
| atomic_npz(job.destination, "seg", read_exr(job.source, ("R",))) | |
| if delete_source: | |
| job.source.unlink() | |
| return job.channel, job.destination | |
| def copy_top_level_metadata(source: Path, destination: Path) -> None: | |
| if source.resolve() == destination.resolve(): | |
| return | |
| destination.mkdir(parents=True, exist_ok=True) | |
| for path in source.iterdir(): | |
| if path.is_file() and path.suffix.lower() in {".json", ".txt"}: | |
| shutil.copy2(path, destination / path.name) | |
| def collect_jobs(source: Path, destination: Path, channels: set[str]) -> list[Job]: | |
| jobs: list[Job] = [] | |
| for camera_dir in sorted(path for path in source.iterdir() if path.is_dir()): | |
| for exr_path in sorted(camera_dir.glob("*.exr")): | |
| identified = classify(exr_path) | |
| if identified is None: | |
| continue | |
| channel, frame = identified | |
| if channel not in channels: | |
| continue | |
| extension = ".jpg" if channel == "rgb" else ".npz" | |
| output = destination / camera_dir.name / channel / f"{frame:04d}{extension}" | |
| jobs.append(Job(exr_path, output, channel)) | |
| return jobs | |
| def validate_outputs(jobs: list[Job]) -> None: | |
| missing = [job.destination for job in jobs if not job.destination.is_file()] | |
| empty = [ | |
| job.destination | |
| for job in jobs | |
| if job.destination.is_file() and job.destination.stat().st_size == 0 | |
| ] | |
| if missing or empty: | |
| examples = [str(path) for path in (missing + empty)[:10]] | |
| raise RuntimeError( | |
| f"Output verification failed: missing={len(missing)}, empty={len(empty)}; " | |
| f"examples={examples}" | |
| ) | |
| def convert_directory( | |
| source: Path, | |
| destination: Path | None, | |
| channels: set[str], | |
| workers: int, | |
| jpeg_quality: int, | |
| delete_source: bool, | |
| ) -> dict[str, int]: | |
| source = source.resolve() | |
| if not source.is_dir(): | |
| raise FileNotFoundError(f"Render directory does not exist: {source}") | |
| destination = source if destination is None else destination.resolve() | |
| destination.mkdir(parents=True, exist_ok=True) | |
| copy_top_level_metadata(source, destination) | |
| jobs = collect_jobs(source, destination, channels) | |
| if not jobs: | |
| raise RuntimeError(f"No recognized EXR passes found under {source}") | |
| counts = {channel: 0 for channel in sorted(channels)} | |
| errors: list[str] = [] | |
| with ThreadPoolExecutor(max_workers=max(1, workers)) as executor: | |
| futures = { | |
| executor.submit(convert, job, jpeg_quality, delete_source): job for job in jobs | |
| } | |
| for future in tqdm( | |
| as_completed(futures), total=len(futures), desc=source.name, unit="file" | |
| ): | |
| job = futures[future] | |
| try: | |
| channel, _ = future.result() | |
| counts[channel] += 1 | |
| except Exception as exc: | |
| errors.append(f"{job.source}: {exc}") | |
| if errors: | |
| raise RuntimeError( | |
| f"{len(errors)} conversion(s) failed. First errors:\n" + "\n".join(errors[:10]) | |
| ) | |
| validate_outputs(jobs) | |
| return counts | |
| def main() -> int: | |
| args = parse_args() | |
| channels = {item.strip().lower() for item in args.channels.split(",") if item.strip()} | |
| unknown = channels - set(PASS_PATTERNS) | |
| if not channels or unknown: | |
| raise ValueError(f"Invalid --channels value; unknown={sorted(unknown)}") | |
| if not args.skip_ply and not {"rgb", "depth"}.issubset(channels): | |
| raise ValueError("PLY generation requires both rgb and depth; use --skip-ply otherwise.") | |
| if args.output_dir is not None and len(args.render_dirs) != 1: | |
| raise ValueError("--output-dir can only be used with one input directory.") | |
| failed = 0 | |
| for source in args.render_dirs: | |
| try: | |
| counts = convert_directory( | |
| source, | |
| args.output_dir, | |
| channels, | |
| args.workers, | |
| args.jpeg_quality, | |
| args.delete_source_exr, | |
| ) | |
| if not args.skip_ply: | |
| render_dir = source if args.output_dir is None else args.output_dir | |
| ply = generate_points3d( | |
| render_dir, | |
| depth_threshold=args.depth_threshold, | |
| max_points=args.max_points, | |
| seed=args.ply_seed, | |
| ) | |
| counts["points3d"] = int(ply["points"]) | |
| print(f"[SUCCESS] {source}: {json.dumps(counts, sort_keys=True)}") | |
| except Exception as exc: | |
| failed += 1 | |
| print(f"[FAILED] {source}: {exc}") | |
| return 1 if failed else 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |