File size: 10,047 Bytes
11c70d1 | 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 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 | """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),
}
@dataclass(frozen=True)
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())
|