ViewSuite-ScanNet / render /render_images.py
JamesK2W's picture
Add files using upload-large-folder tool
dd18159 verified
Raw History Blame
4.73 kB
#!/usr/bin/env python3
"""Re-create the images of the ViewSuite ScanNet corpus from the stored cameras.
The task files reference 256 x 256 PNG renders of ScanNet meshes, which this repository does not distribute
(ScanNet Terms of Use). Every image is a deterministic Habitat-Sim render of a ScanNet v2 mesh
(<scans>/<scene>/<scene>_vh_clean.ply) at the camera stored in render/images.jsonl (OpenCV camera-to-world
matrix `c2w` and intrinsics `K`, the same values as `image_detail` in the task files). When the corpus was built,
every image re-rendered pixel-identically with this renderer; other GPUs or drivers can differ slightly, so the
script checks every image against the pixel hash in the manifest and reports matches and differences.
python render/render_images.py --out corpus --scans <ScanNet v2 scans dir> --gpu 0
python render/render_images.py --out corpus --verify-only # only hash existing images
Requirements: the ViewSuite code release on PYTHONPATH (view_agent) and its Habitat-Sim environment (the one the
ScanNet render service uses), a GPU with OpenGL/EGL, and the ScanNet v2 meshes, obtained from ScanNet under its
Terms of Use. Prints a JSON summary; exits with status 1 if any image is missing or differs.
pixel_sha256 = SHA-256 of the decoded image as height x width x 3 uint8 RGB bytes (row-major), so it does not
depend on the PNG encoder; file_sha256 is the hash of the original PNG file.
"""
import argparse
import collections
import hashlib
import json
import os
import sys
import numpy as np
from PIL import Image
def pixel_sha256(arr):
a = np.ascontiguousarray(np.asarray(arr)[..., :3].astype(np.uint8))
return hashlib.sha256(a.tobytes()).hexdigest()
def main():
here = os.path.dirname(os.path.abspath(__file__))
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--manifest", default=os.path.join(here, "images.jsonl"))
ap.add_argument("--out", required=True, help="corpus directory: images are written below it at their paths")
ap.add_argument("--scans", default=None, help="ScanNet v2 scans directory (<scans>/<scene>/<scene>_vh_clean.ply)")
ap.add_argument("--gpu", type=int, default=0)
ap.add_argument("--scenes", default=None, help="comma-separated subset of scene ids")
ap.add_argument("--verify-only", action="store_true")
ap.add_argument("--overwrite", action="store_true", help="re-render images that already exist")
a = ap.parse_args()
jobs = [json.loads(line) for line in open(a.manifest)]
if a.scenes:
keep = set(a.scenes.split(","))
jobs = [j for j in jobs if j["scene_id"] in keep]
by_scene = collections.defaultdict(list)
for j in jobs:
by_scene[j["scene_id"]].append(j)
stats = collections.Counter()
bad = []
for scene in sorted(by_scene):
todo = [j for j in by_scene[scene]
if a.overwrite or not os.path.exists(os.path.join(a.out, j["path"]))]
if todo and not a.verify_only:
if not a.scans:
raise SystemExit("--scans is required to render")
from view_agent.envs.scannet._common.render.habitat_render import HabitatRenderer
ply = os.path.join(a.scans, scene, f"{scene}_vh_clean.ply")
r = HabitatRenderer(ply, gpu_device_id=a.gpu, width=256, height=256)
try:
for j in todo:
img = np.asarray(r.render_image_from_cam_param(np.asarray(j["K"]), np.asarray(j["c2w"]),
j["width"], j["height"]))[..., :3]
dst = os.path.join(a.out, j["path"])
os.makedirs(os.path.dirname(dst), exist_ok=True)
Image.fromarray(img.astype(np.uint8)).save(dst)
stats["rendered"] += 1
finally:
r.close()
for j in by_scene[scene]:
dst = os.path.join(a.out, j["path"])
if not os.path.exists(dst):
stats["missing"] += 1
bad.append({"path": j["path"], "problem": "missing"})
continue
with Image.open(dst) as im:
h = pixel_sha256(np.asarray(im.convert("RGB")))
if h == j["pixel_sha256"]:
stats["pixel_identical"] += 1
else:
stats["different"] += 1
bad.append({"path": j["path"], "problem": "pixels differ"})
summary = {"images": len(jobs), **stats, "problems": bad[:50]}
print(json.dumps(summary, indent=1))
return 0 if stats["pixel_identical"] == len(jobs) else 1
if __name__ == "__main__":
sys.exit(main())