File size: 4,171 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 | """Image assets for the paper-style overview figure (one example test object)."""
import os
import sys
import glob
import json
import argparse
import numpy as np
import torch
import imageio.v3 as iio
import matplotlib
import nvdiffrast.torch as dr
from PIL import Image
from render_compare import load_mesh, render_mesh, render_points, GT_ROOT
from sem_eval import crop
O = "/home/hubin/trellis_work/outputs"
F = "/home/hubin/data/fMRI-Shape"
def token_rgb(tokens, basis=None):
patches = tokens[5:].astype(np.float32) # 1 CLS + 4 registers, then 32 x 32 patches
if basis is None:
mu = patches.mean(0)
_, _, vt = np.linalg.svd(patches - mu, full_matrices=False)
proj = (patches - mu) @ vt[:3].T
basis = (mu, vt[:3], proj.min(0), proj.max(0))
mu, v, lo, hi = basis
rgb = np.clip(((patches - mu) @ v.T - lo) / (hi - lo + 1e-8), 0, 1).reshape(32, 32, 3)
return Image.fromarray((rgb * 255).astype(np.uint8)).resize((256, 256), Image.NEAREST), basis
def transparent(img, thresh=250):
a = np.asarray(img.convert("RGBA")).copy()
a[..., 3] = np.where((a[..., :3] >= thresh).all(-1), 0, 255)
return Image.fromarray(a)
def main():
p = argparse.ArgumentParser()
p.add_argument("--obj", default="02691156/cbb5ed444249f0a9e90916c8815b5c43")
p.add_argument("--other", default="02691156/d6cc7ffd165de05e2e2de556c136fbc8",
help="another test object of the same category (identification panel)")
p.add_argument("--out_dir", default=f"{O}/fig_assets")
args = p.parse_args()
os.makedirs(args.out_dir, exist_ok=True)
cat, uid = args.obj.split("/")
name = f"{cat}_{uid}"
fmri = np.load(f"{F}/sub-0001/npy_data/{args.obj}.npy")
cmap = matplotlib.colormaps["RdBu_r"]
for t in (2, 4, 6):
x = fmri[t]
s = np.percentile(np.abs(x[x != 0]), 99) if (x != 0).any() else 1
rgb = cmap(np.clip(x / s, -1, 1) * 0.5 + 0.5)[..., :3]
rgb[x == 0] = 1.0
Image.fromarray((rgb * 255).astype(np.uint8)).save(f"{args.out_dir}/fmri_t{t}.png")
frames = iio.imread(f"{F}/stimuli_test/stimuli/{args.obj}.mp4")
transparent(crop(Image.fromarray(frames[24]), margin=0.25), 245).save(f"{args.out_dir}/stimulus.png")
Image.open(f"{F}/trellis2_cond/images/{args.obj}/f024.png").convert("RGB").resize((256, 256)).save(
f"{args.out_dir}/stimulus_prep.png")
gt_tok = np.load(f"{F}/trellis2_cond/tokens/{args.obj}.npy", mmap_mode="r")[1]
img, basis = token_rgb(np.asarray(gt_tok))
img.save(f"{args.out_dir}/tokens_gt.png")
test_ids = open(f"{F}/mapper_feats/test_ids.txt").read().split()
pred_tok = np.load(f"{O}/ridge/ridge_k64_rescaled/tokens.npy", mmap_mode="r")[test_ids.index(args.obj)]
token_rgb(np.asarray(pred_tok), basis)[0].save(f"{args.out_dir}/tokens_pred.png")
ctx = dr.RasterizeCudaContext()
for key, src in [("ours", "cfg/ridge_k64_rescaled_cfg30"), ("mind3d", "mind3d_sub01"),
("oracle", "upper_bound_512_f24")]:
row = {r["id"]: r for r in json.load(open(f"{O}/{src}/metrics.json"))["rows"]}[args.obj]
path = [q for q in glob.glob(f"{O}/{src}/meshes/{name}.*") if q.endswith((".ply", ".obj"))][0]
v, f = load_mesh(path, row["up"], row["azimuth"])
transparent(crop(render_mesh(ctx, v, f, res=512), margin=0.12)).save(f"{args.out_dir}/mesh_{key}.png")
print(key, f"CD {row['cd'] * 1e3:.2f}")
for tag, u in [("", uid), ("_other", args.other.split("/")[1])]:
gt = np.load(glob.glob(f"{GT_ROOT}/{cat}/_/*/{u}.npy")[0])
transparent(crop(render_points(gt, res=512), margin=0.12)).save(f"{args.out_dir}/gt_points{tag}.png")
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "mapper"))
from pca_tools import get_pca, project
pca = get_pca()
toks = torch.from_numpy(np.stack([np.asarray(pred_tok), np.asarray(gt_tok)])).cuda()
c_pred, c_gt = project(toks, pca, 16).cpu().numpy()
json.dump({"obj": args.obj, "coef_pred": c_pred.tolist(), "coef_gt": c_gt.tolist()},
open(f"{args.out_dir}/meta.json", "w"))
if __name__ == "__main__":
main()
|