File size: 10,707 Bytes
7c61ee6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Render side-by-side comparison sheets: stimulus | GT points | each method's mesh, aligned to the GT frame."""
import os
import glob
import json
import argparse
from concurrent.futures import ThreadPoolExecutor

import numpy as np
import torch
import trimesh
import nvdiffrast.torch as dr
from PIL import Image, ImageDraw, ImageFont

from eval_shape import UP_MAPS, rot_y

O = "/home/hubin/trellis_work/outputs"
GT_ROOT = "/home/hubin/data/ShapeNetCore.v2.PC15k/ShapeNetCore.v2.PC15k"
STIM_DIR = f"{O}/upper_bound_512_f24/inputs"
GROUP_COLORS = {"input": (120, 120, 120), "baseline": (200, 40, 40), "ours": (30, 150, 60),
                "ours_retrieval": (230, 140, 20), "reference": (150, 150, 150)}
METHODS = [  # (label, mesh dir, key used for meshes/ on HF, group)
    ("MinD-3D (baseline)", f"{O}/mind3d_sub01", "mind3d_official", "baseline"),
    ("Ours: ridge, CFG 7.5", f"{O}/ridge/ridge_k64_rescaled", "ridge_k64_rescaled", "ours"),
    ("Ours: ridge, CFG 30", f"{O}/cfg/ridge_k64_rescaled_cfg30", "ridge_k64_rescaled_cfg30", "ours"),
    ("Ours: v2 ens, CFG 20 (L)", f"{O}/final/v2_ens5_coef_rescaled_cfg20", "v2ens5_coef_rescaled_cfg20", "ours"),
    ("Ours: cls-first, CFG 30 (L)", f"{O}/final/clsfirst_clsfirst_knn_resid_k64_rescaled_cfg30",
     "clsfirst_knn_resid_k64_rescaled_cfg30", "ours"),
    ("Ours: retrieval*", f"{O}/gen_retrieval_v0_c01", "v0_retrieval", "ours_retrieval"),
    ("Ref: category mean", f"{O}/diag/category_mean", "diag_category_mean", "reference"),
    ("Ref: oracle GT image", f"{O}/upper_bound_512_f24", "oracle_gt_image", "reference"),
]
CAT_NAMES = {"02691156": "airplane", "02828884": "bench", "02933112": "cabinet", "02958343": "car",
             "03001627": "chair", "03211117": "display", "03636649": "lamp", "03691459": "speaker",
             "04090263": "rifle", "04256520": "sofa", "04379243": "table", "04401088": "phone",
             "04530566": "watercraft"}
CELL = 256
BAND_H = 6
LABEL_H = 44
SEP = 3


def font(size):
    try:
        return ImageFont.load_default(size=size)
    except TypeError:
        return ImageFont.load_default()


def look_at(eye, target=(0, 0, 0), up=(0, 1, 0)):
    eye, target, up = map(np.asarray, (eye, target, up))
    f = target - eye
    f = f / np.linalg.norm(f)
    s = np.cross(f, up)
    s = s / np.linalg.norm(s)
    u = np.cross(s, f)
    m = np.eye(4)
    m[0, :3], m[1, :3], m[2, :3] = s, u, -f
    m[:3, 3] = -m[:3, :3] @ eye
    return m


def perspective(fovy_deg, near=0.1, far=10.0):
    f = 1 / np.tan(np.deg2rad(fovy_deg) / 2)
    return np.array([[f, 0, 0, 0], [0, f, 0, 0],
                     [0, 0, (far + near) / (near - far), 2 * far * near / (near - far)], [0, 0, -1, 0]])


AZ, EL, DIST = np.deg2rad(35), np.deg2rad(25), 2.0
EYE = DIST * np.array([np.cos(EL) * np.sin(AZ), np.sin(EL), np.cos(EL) * np.cos(AZ)])
VIEW = look_at(EYE)
MVP = torch.tensor(perspective(32) @ VIEW, dtype=torch.float32, device="cuda")
LIGHT = torch.tensor(EYE / np.linalg.norm(EYE) + np.array([0.3, 0.6, 0.0]), dtype=torch.float32, device="cuda")
LIGHT = LIGHT / LIGHT.norm()


def normalize(points_for_stats, v):
    c = points_for_stats.mean(0)
    r = np.max(np.linalg.norm(points_for_stats - c, axis=1))
    return (v - c) / (2 * r)


def load_mesh(path, up, az):
    mesh = trimesh.load(path, force="mesh", process=False)
    v = np.asarray(mesh.vertices, dtype=np.float64)
    pts = trimesh.sample.sample_surface(mesh, 4096, seed=0)[0]
    v = normalize(pts, v) @ (rot_y(az) @ UP_MAPS[up]).T
    return v.astype(np.float32), np.asarray(mesh.faces, dtype=np.int32)


FACE_CHUNK = 4_000_000


@torch.no_grad()
def render_mesh(ctx, v, f, res=CELL, ss=2, mvp=None, light=None, base=(0.62, 0.70, 0.85)):
    mvp = MVP if mvp is None else mvp
    light = LIGHT if light is None else light
    v = torch.from_numpy(v).cuda()
    f = torch.from_numpy(f).cuda()
    clip = torch.cat([v, torch.ones_like(v[:, :1])], 1) @ mvp.T
    depth, tri = None, None
    for start in range(0, len(f), FACE_CHUNK):  # nvdiffrast crashes on very large meshes (>~16M faces)
        rast, _ = dr.rasterize(ctx, clip[None].contiguous(), f[start:start + FACE_CHUNK].contiguous(),
                               resolution=[res * ss, res * ss])
        t = rast[0, ..., 3].long() - 1
        z = torch.where(t >= 0, rast[0, ..., 2], torch.full_like(rast[0, ..., 2], float("inf")))
        t = torch.where(t >= 0, t + start, t)
        if depth is None:
            depth, tri = z, t
        else:
            closer = z < depth
            depth, tri = torch.where(closer, z, depth), torch.where(closer, t, tri)
    fn = torch.cross(v[f[:, 1]] - v[f[:, 0]], v[f[:, 2]] - v[f[:, 0]], dim=1)
    fn = fn / (fn.norm(dim=1, keepdim=True) + 1e-12)
    n = fn[tri.clamp_min(0)]
    shade = 0.25 + 0.75 * (n @ light).abs()
    color = torch.tensor(base, device="cuda") * shade[..., None]
    img = torch.where((tri >= 0)[..., None], color, torch.ones_like(color))
    img = img.flip(0).permute(2, 0, 1)[None]
    img = torch.nn.functional.avg_pool2d(img, ss)[0].permute(1, 2, 0)
    return Image.fromarray((img.clamp(0, 1).cpu().numpy() * 255).astype(np.uint8))


def render_points(p, res=CELL):
    p = normalize(p, p)
    h = np.concatenate([p, np.ones((len(p), 1))], 1) @ (perspective(32) @ VIEW).T
    xy = h[:, :2] / h[:, 3:]
    depth = h[:, 2] / h[:, 3]
    px = ((xy[:, 0] + 1) / 2 * (res - 1)).round().astype(int)
    py = ((1 - (xy[:, 1] + 1) / 2) * (res - 1)).round().astype(int)
    img = np.full((res, res, 3), 255, np.uint8)
    order = np.argsort(-depth)
    d = (depth - depth.min()) / (np.ptp(depth) + 1e-9)
    for i in order:
        x, y = px[i], py[i]
        if 0 <= x < res - 1 and 0 <= y < res - 1:
            g = int(40 + 150 * d[i])
            img[y:y + 2, x:x + 2] = (g, g, int(g * 0.8 + 50))
    return Image.fromarray(img)


def cell_with_label(img, text, group, sub=None):
    out = Image.new("RGB", (CELL, BAND_H + CELL + LABEL_H), "white")
    ImageDraw.Draw(out).rectangle([0, 0, CELL, BAND_H - 1], fill=GROUP_COLORS[group])
    out.paste(img.resize((CELL, CELL)), (0, BAND_H))
    d = ImageDraw.Draw(out)
    f = font(15)
    d.text(((CELL - d.textlength(text, font=f)) / 2, BAND_H + CELL + 3), text, fill=(0, 0, 0), font=f)
    if sub:
        d.text(((CELL - d.textlength(sub, font=f)) / 2, BAND_H + CELL + 22), sub, fill=GROUP_COLORS[group], font=f)
    return out


def hstack(cells):
    row = Image.new("RGB", (len(cells) * (CELL + SEP) - SEP, cells[0].height), (225, 225, 225))
    for i, c in enumerate(cells):
        row.paste(c, (i * (CELL + SEP), 0))
    return row


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--out_dir", default=f"{O}/renders")
    parser.add_argument("--test_list", default="/home/hubin/data/fMRI-Shape/annotations/core_test_list.txt")
    parser.add_argument("--limit", type=int, default=0)
    parser.add_argument("--shard", type=int, default=0, help="shards split by category")
    parser.add_argument("--num_shards", type=int, default=1)
    parser.add_argument("--overview_only", action="store_true", help="assemble overview.png from per_object/")
    args = parser.parse_args()
    if args.overview_only:
        return build_overview(args.out_dir)
    os.makedirs(f"{args.out_dir}/per_object", exist_ok=True)

    gt_paths = {os.path.basename(p)[:-4]: p for p in glob.glob(f"{GT_ROOT}/*/_/*/*.npy")}
    rows = {name: {r["id"]: r for r in json.load(open(f"{d}/metrics.json"))["rows"]} for name, d, _, _ in METHODS}
    ids = [l.strip() for l in open(args.test_list) if l.strip()]
    ids = [i for i in ids if i.split("/")[1] in gt_paths]
    cats = sorted({i.split("/")[0] for i in ids})[args.shard::args.num_shards]
    ids = [i for i in ids if i.split("/")[0] in cats]
    if args.limit:
        ids = ids[:args.limit]
    ctx = dr.RasterizeCudaContext()
    pool = ThreadPoolExecutor(8)

    by_cat = {}
    for n, obj in enumerate(ids):
        cat, uid = obj.split("/")
        name = f"{cat}_{uid}"
        futures = []
        for m, d, key, group in METHODS:
            r = rows[m][obj]
            cache = f"{args.out_dir}/cells/{key}/{name}.png"
            if os.path.exists(cache):
                futures.append((m, group, r, cache, None))
                continue
            path = [p for p in glob.glob(f"{d}/meshes/{name}.*") if p.endswith((".ply", ".obj"))][0]
            futures.append((m, group, r, cache, pool.submit(load_mesh, path, r["up"], r["azimuth"])))
        cells = [cell_with_label(Image.open(f"{STIM_DIR}/{name}.png").convert("RGB"), "stimulus (frame 24)", "input"),
                 cell_with_label(render_points(np.load(gt_paths[uid])), "GT point cloud", "input")]
        for m, group, r, cache, fut in futures:
            if fut is None:
                img = Image.open(cache)
            else:
                v, f = fut.result()
                img = render_mesh(ctx, v, f)
                os.makedirs(os.path.dirname(cache), exist_ok=True)
                img.save(cache)
            cells.append(cell_with_label(img, m, group, f"CD {r['cd'] * 1e3:.1f}"))
        row = hstack(cells)
        row.save(f"{args.out_dir}/per_object/{name}.png")
        by_cat.setdefault(cat, []).append(row)
        print(f"[{n + 1}/{len(ids)}] {obj}", flush=True)

    for cat, rs in by_cat.items():
        stack(rs, f"{cat} {CAT_NAMES[cat]}  (sub-01 test set)").save(f"{args.out_dir}/{cat}_{CAT_NAMES[cat]}.png")


def stack(rows, title, title_h=64, gap=10):
    sheet = Image.new("RGB", (rows[0].width, title_h + sum(r.height + gap for r in rows)), "white")
    d = ImageDraw.Draw(sheet)
    d.text((10, 6), title, fill=(0, 0, 0), font=font(24))
    x = 10
    for text, group in [("green = Ours (fMRI only; (L) = category labels used in training)", "ours"), ("orange = Ours retrieval (*uses train-set GT tokens)",
                        "ours_retrieval"), ("red = MinD-3D baseline", "baseline"),
                        ("gray = references, not from fMRI", "reference"), ("number = CD x1e-3, lower is better", "input")]:
        d.rectangle([x, 40, x + 14, 54], fill=GROUP_COLORS[group])
        d.text((x + 20, 38), text, fill=(0, 0, 0), font=font(16))
        x += 40 + d.textlength(text, font=font(16))
    y = title_h
    for r in rows:
        sheet.paste(r, (0, y))
        y += r.height + gap
    return sheet


def build_overview(out_dir):
    first = {}
    for p in sorted(glob.glob(f"{out_dir}/per_object/*.png")):
        first.setdefault(os.path.basename(p).split("_")[0], p)
    rows = [Image.open(p) for _, p in sorted(first.items())]
    stack(rows, "Overview: first test object of each category (sub-01 test set)").save(f"{out_dir}/overview.png")


if __name__ == "__main__":
    main()