File size: 4,807 Bytes
1b4b289
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Render the observation images of the VGD training trajectories from their stored camera poses.

The trajectories store poses, not images. Every observation is a 256 x 256 Habitat-Sim render of a ScanNet v2 mesh
at a camera pose [tx, ty, tz, rx, ry, rz] (camera-to-world: position in meters, rotation
scipy.spatial.transform.Rotation.from_euler("xyz", [rx, ry, rz], degrees=True), OpenCV camera axes) with the
intrinsics of the scene's views (render/scene_intrinsics.jsonl, the same K as in the ViewSuite-ScanNet task files).

    # view-graph node images, at the paths the graph and the SFT image map use (images/<scene>/<name>.png)
    python render/render_views.py --graph graph/round_2.json --out <dir> --scans <ScanNet scans dir> --gpu 0
    # episode observation frames (frames/<scene>/<name>.png)
    python render/render_views.py --episodes episodes/round_0.jsonl --out <dir> --scans <ScanNet scans dir>
    # list the jobs and check poses without rendering
    python render/render_views.py --graph graph/round_2.json --out <dir> --dry-run

Requirements: the ViewSuite code release on PYTHONPATH (view_agent), its Habitat-Sim environment, a GPU with
OpenGL/EGL, and the ScanNet v2 meshes (ScanNet Terms of Use). The poses are rounded to float64 through Euler angles,
so a re-render can differ from the original frame by floating-point rounding of the camera.
"""
import argparse
import collections
import json
import os
import sys

import numpy as np


def pose6_to_c2w(pose):
    from scipy.spatial.transform import Rotation
    p = np.asarray(pose, dtype=np.float64).reshape(6)
    m = np.eye(4)
    m[:3, :3] = Rotation.from_euler("xyz", p[3:], degrees=True).as_matrix()
    m[:3, 3] = p[:3]
    return m


def jobs_from_graph(path):
    g = json.load(open(path))
    seen = set()
    for n in g["nodes"]:
        if n.get("image") and n["image"] not in seen:
            seen.add(n["image"])
            yield n["scene"], n["pose"], n["image"]


def jobs_from_episodes(path):
    seen = set()
    for line in open(path):
        e = json.loads(line)
        cands = [(e["init"]["pose"], e["init"].get("image"))]
        cands += [(t["pose_after"], t.get("image")) for t in e["turns"]]
        for pose, img in cands:
            if img and img not in seen:
                seen.add(img)
                yield e["scene_id"], pose, img


def main():
    here = os.path.dirname(os.path.abspath(__file__))
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--graph", default=None)
    ap.add_argument("--episodes", nargs="*", default=[])
    ap.add_argument("--intrinsics", default=os.path.join(here, "scene_intrinsics.jsonl"))
    ap.add_argument("--out", required=True)
    ap.add_argument("--scans", default=None)
    ap.add_argument("--gpu", type=int, default=0)
    ap.add_argument("--scenes", default=None)
    ap.add_argument("--dry-run", action="store_true")
    a = ap.parse_args()
    K = {}
    for line in open(a.intrinsics):
        r = json.loads(line)
        K[r["scene_id"]] = r["K"]
    jobs = []
    if a.graph:
        jobs += list(jobs_from_graph(a.graph))
    for ep in a.episodes:
        jobs += list(jobs_from_episodes(ep))
    if a.scenes:
        keep = set(a.scenes.split(","))
        jobs = [j for j in jobs if j[0] in keep]
    by_scene = collections.defaultdict(list)
    for scene, pose, rel in jobs:
        by_scene[scene].append((pose, rel))
    missing_k = sorted(s for s in by_scene if s not in K)
    if missing_k:
        raise SystemExit(f"no intrinsics for {len(missing_k)} scenes, e.g. {missing_k[:3]}")
    stats = collections.Counter(jobs=len(jobs), scenes=len(by_scene))
    if a.dry_run:
        print(json.dumps(stats))
        return 0
    if not a.scans:
        raise SystemExit("--scans is required to render")
    from PIL import Image
    from view_agent.envs.scannet._common.render.habitat_render import HabitatRenderer
    for scene in sorted(by_scene):
        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 pose, rel in by_scene[scene]:
                dst = os.path.join(a.out, rel)
                if os.path.exists(dst):
                    stats["exists"] += 1
                    continue
                img = np.asarray(r.render_image_from_cam_param(np.asarray(K[scene]), pose6_to_c2w(pose), 256, 256))
                os.makedirs(os.path.dirname(dst), exist_ok=True)
                Image.fromarray(img[..., :3].astype(np.uint8)).save(dst)
                stats["rendered"] += 1
        finally:
            r.close()
    print(json.dumps(stats))
    return 0


if __name__ == "__main__":
    sys.exit(main())