"""Compose the final camera-map collage from the kept samples (after web review). - NO padding: each image keeps its native aspect ratio (no black frame). The perspective field is computed on the 640x640 model view, then CROPPED back to the un-padded region so it aligns with the native-aspect image. - Justified-rows layout (flexbox-style photo collage): each row is scaled to the same width; row heights vary slightly. Beautiful, gap-only, no black frames. """ import argparse import io import json import os import sys import numpy as np from PIL import Image import os as _os; sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) import gallery_lib as G ROOT = "/data/NTU_slab/kliao/code/Puffin_Final/Puffin2/output" PICKS = os.path.join(ROOT, "gallery_picks.json") def render_nopad(pil, roll, pitch, vfov, k1, panel_h=340, sep=6): """Return an RGB array [up | lat] at native aspect, no padding.""" import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from scripts.camera.visualization.viz2d import plot_vector_fields, plot_latitudes w, h = pil.size if w >= h: nw, nh = 640, max(1, round(h * 640 / w)) else: nh, nw = 640, max(1, round(w * 640 / h)) img = np.asarray(pil.resize((nw, nh))).astype(np.float32) / 255.0 up, lat = G.compute_fields(roll, pitch, vfov, k1, h=640, w=640) y0, x0 = (640 - nh) // 2, (640 - nw) // 2 up_c = up[:, y0:y0 + nh, x0:x0 + nw] lat_c = lat[:, y0:y0 + nh, x0:x0 + nw] def one(overlay): fig = plt.figure(figsize=(nw / 100, nh / 100), dpi=100) ax = fig.add_axes([0, 0, 1, 1]); ax.set_axis_off() ax.imshow(img); ax.set_xlim([0, nw]); ax.set_ylim([nh, 0]) overlay(ax) fig.canvas.draw() a = np.asarray(fig.canvas.buffer_rgba())[..., :3].copy() plt.close(fig) return a up_img = one(lambda ax: plot_vector_fields([up_c], axes=[ax])) lat_img = one(lambda ax: plot_latitudes([lat_c[0] * G.DEG], is_radians=False, axes=[ax])) H = min(up_img.shape[0], lat_img.shape[0]) pair = np.concatenate([up_img[:H], 255 * np.ones((H, sep, 3), np.uint8), lat_img[:H]], axis=1) im = Image.fromarray(pair) scale = panel_h / im.height return im.resize((max(1, round(im.width * scale)), panel_h)) def _layout(items, W, h0, gap): """Greedy justified rows at width W using target row height h0. Returns (rows, row_heights, total_height).""" rows, cur, cw = [], [], 0.0 for im in items: w = h0 * im.width / im.height if cur and cw + gap + w > W: rows.append(cur); cur, cw = [], 0.0 cur.append(im); cw += (gap if len(cur) > 1 else 0) + w if cur: rows.append(cur) heights = [(W - gap * (len(r) + 1)) / sum(im.width / im.height for im in r) for r in rows] return rows, heights, sum(heights) + gap * (len(rows) + 1) def _balanced_rows(items, R): """Partition items into R contiguous rows with ~equal total aspect ratio, so every row is packed to a similar height (no sparse, stretched last row).""" asp = [im.width / im.height for im in items] cum, s = [], 0.0 for a in asp: s += a; cum.append(s) total = cum[-1] rows, start = [], 0 for i in range(1, R): thr = total * i / R j = min(range(start, len(items)), key=lambda k: abs(cum[k] - thr)) j = max(j, start) # non-empty rows.append(items[start:j + 1]); start = j + 1 if start >= len(items): break if start < len(items): rows.append(items[start:]) return [r for r in rows if r] def aspect_collage(items, W=3600, ratio=(4, 3), gap=10, bg=(245, 246, 248)): """Collage at target aspect W:H = ratio[0]:ratio[1] using BALANCED rows (each row ~equal total aspect -> uniform heights, no giant single-item row). R = round(sqrt(Ht*sum_aspect/W)); layout height ~= Ht, tiny overflow cropped.""" Ht = int(round(W * ratio[1] / ratio[0])) total_asp = sum(im.width / im.height for im in items) R = max(1, round((Ht * total_asp / W) ** 0.5)) rows = _balanced_rows(items, R) heights = [(W - gap * (len(r) + 1)) / sum(im.width / im.height for im in r) for r in rows] Hlay = int(sum(heights) + gap * (len(rows) + 1)) canvas = Image.new("RGB", (W, max(Hlay, Ht) + 2), bg) y = gap for row, h in zip(rows, heights): h = int(round(h)); x = gap for im in row: w = max(1, round(h * im.width / im.height)) canvas.paste(im.resize((w, h)), (x, y)) x += w + gap y += h + gap return canvas.crop((0, 0, W, Ht)) def main(): ap = argparse.ArgumentParser() ap.add_argument("--exclude", default="", help="comma-separated indices to drop") ap.add_argument("--n_show", type=int, default=0, help="render only first N picks (0=all kept)") ap.add_argument("--n_collage", type=int, default=0, help="use N panels for collage (0=all)") ap.add_argument("--out", default=os.path.join(ROOT, "imagenet1k_camera_map_gallery.png")) ap.add_argument("--target_w", type=int, default=3400) ap.add_argument("--ratio", default="4:3", help='collage aspect W:H, e.g. 4:3, 1:1, 16:9') args = ap.parse_args() rw, rh = (int(x) for x in args.ratio.split(":")) excl = set(int(x) for x in args.exclude.split(",") if x.strip() != "") meta = [m for m in json.load(open(PICKS)) if m["idx"] not in excl] if args.n_show: meta = meta[:args.n_show] print(f"rendering {len(meta)} panels ...") mega = os.environ.get("GALLERY_DATASET") == "megalith" imgs = {} if mega else (print("loading source images ...") or G.load_source_images(8)) items = [] for m in meta: b = G.fetch_url(m["url"]) if mega else imgs.get(m["val"]) if not b: continue try: pil = Image.open(io.BytesIO(b)).convert("RGB") except Exception: continue items.append(render_nopad(pil, m["roll"], m["pitch"], m["vfov"], 0.0)) print(f"rendered {len(items)} panels") # optionally pick N_collage of them spread across aspect ratio for variety if args.n_collage and args.n_collage < len(items): order = sorted(range(len(items)), key=lambda i: items[i].width / items[i].height) step = len(order) / args.n_collage sel = sorted(order[int(k * step)] for k in range(args.n_collage)) items = [items[i] for i in sel] print(f"selected {len(items)} for collage (aspect-spread)") col = aspect_collage(items, W=args.target_w, ratio=(rw, rh)) col.save(args.out) print("saved collage ->", args.out, col.size) if __name__ == "__main__": main()