KangLiao commited on
Commit
0b5a123
·
verified ·
1 Parent(s): 175a3de

Upload analysis/camera_map_skill/make_collage.py with huggingface_hub

Browse files
analysis/camera_map_skill/make_collage.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compose the final camera-map collage from the kept samples (after web review).
2
+
3
+ - NO padding: each image keeps its native aspect ratio (no black frame). The
4
+ perspective field is computed on the 640x640 model view, then CROPPED back to
5
+ the un-padded region so it aligns with the native-aspect image.
6
+ - Justified-rows layout (flexbox-style photo collage): each row is scaled to the
7
+ same width; row heights vary slightly. Beautiful, gap-only, no black frames.
8
+ """
9
+ import argparse
10
+ import io
11
+ import json
12
+ import os
13
+ import sys
14
+
15
+ import numpy as np
16
+ from PIL import Image
17
+
18
+ import os as _os; sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
19
+ import gallery_lib as G
20
+
21
+ ROOT = "/data/NTU_slab/kliao/code/Puffin_Final/Puffin2/output"
22
+ PICKS = os.path.join(ROOT, "gallery_picks.json")
23
+
24
+
25
+ def render_nopad(pil, roll, pitch, vfov, k1, panel_h=340, sep=6):
26
+ """Return an RGB array [up | lat] at native aspect, no padding."""
27
+ import matplotlib
28
+ matplotlib.use("Agg")
29
+ import matplotlib.pyplot as plt
30
+ from scripts.camera.visualization.viz2d import plot_vector_fields, plot_latitudes
31
+ w, h = pil.size
32
+ if w >= h:
33
+ nw, nh = 640, max(1, round(h * 640 / w))
34
+ else:
35
+ nh, nw = 640, max(1, round(w * 640 / h))
36
+ img = np.asarray(pil.resize((nw, nh))).astype(np.float32) / 255.0
37
+ up, lat = G.compute_fields(roll, pitch, vfov, k1, h=640, w=640)
38
+ y0, x0 = (640 - nh) // 2, (640 - nw) // 2
39
+ up_c = up[:, y0:y0 + nh, x0:x0 + nw]
40
+ lat_c = lat[:, y0:y0 + nh, x0:x0 + nw]
41
+
42
+ def one(overlay):
43
+ fig = plt.figure(figsize=(nw / 100, nh / 100), dpi=100)
44
+ ax = fig.add_axes([0, 0, 1, 1]); ax.set_axis_off()
45
+ ax.imshow(img); ax.set_xlim([0, nw]); ax.set_ylim([nh, 0])
46
+ overlay(ax)
47
+ fig.canvas.draw()
48
+ a = np.asarray(fig.canvas.buffer_rgba())[..., :3].copy()
49
+ plt.close(fig)
50
+ return a
51
+ up_img = one(lambda ax: plot_vector_fields([up_c], axes=[ax]))
52
+ lat_img = one(lambda ax: plot_latitudes([lat_c[0] * G.DEG], is_radians=False, axes=[ax]))
53
+ H = min(up_img.shape[0], lat_img.shape[0])
54
+ pair = np.concatenate([up_img[:H], 255 * np.ones((H, sep, 3), np.uint8), lat_img[:H]], axis=1)
55
+ im = Image.fromarray(pair)
56
+ scale = panel_h / im.height
57
+ return im.resize((max(1, round(im.width * scale)), panel_h))
58
+
59
+
60
+ def _layout(items, W, h0, gap):
61
+ """Greedy justified rows at width W using target row height h0.
62
+ Returns (rows, row_heights, total_height)."""
63
+ rows, cur, cw = [], [], 0.0
64
+ for im in items:
65
+ w = h0 * im.width / im.height
66
+ if cur and cw + gap + w > W:
67
+ rows.append(cur); cur, cw = [], 0.0
68
+ cur.append(im); cw += (gap if len(cur) > 1 else 0) + w
69
+ if cur:
70
+ rows.append(cur)
71
+ heights = [(W - gap * (len(r) + 1)) / sum(im.width / im.height for im in r) for r in rows]
72
+ return rows, heights, sum(heights) + gap * (len(rows) + 1)
73
+
74
+
75
+ def _balanced_rows(items, R):
76
+ """Partition items into R contiguous rows with ~equal total aspect ratio, so
77
+ every row is packed to a similar height (no sparse, stretched last row)."""
78
+ asp = [im.width / im.height for im in items]
79
+ cum, s = [], 0.0
80
+ for a in asp:
81
+ s += a; cum.append(s)
82
+ total = cum[-1]
83
+ rows, start = [], 0
84
+ for i in range(1, R):
85
+ thr = total * i / R
86
+ j = min(range(start, len(items)), key=lambda k: abs(cum[k] - thr))
87
+ j = max(j, start) # non-empty
88
+ rows.append(items[start:j + 1]); start = j + 1
89
+ if start >= len(items):
90
+ break
91
+ if start < len(items):
92
+ rows.append(items[start:])
93
+ return [r for r in rows if r]
94
+
95
+
96
+ def aspect_collage(items, W=3600, ratio=(4, 3), gap=10, bg=(245, 246, 248)):
97
+ """Collage at target aspect W:H = ratio[0]:ratio[1] using BALANCED rows
98
+ (each row ~equal total aspect -> uniform heights, no giant single-item row).
99
+ R = round(sqrt(Ht*sum_aspect/W)); layout height ~= Ht, tiny overflow cropped."""
100
+ Ht = int(round(W * ratio[1] / ratio[0]))
101
+ total_asp = sum(im.width / im.height for im in items)
102
+ R = max(1, round((Ht * total_asp / W) ** 0.5))
103
+ rows = _balanced_rows(items, R)
104
+ heights = [(W - gap * (len(r) + 1)) / sum(im.width / im.height for im in r) for r in rows]
105
+ Hlay = int(sum(heights) + gap * (len(rows) + 1))
106
+ canvas = Image.new("RGB", (W, max(Hlay, Ht) + 2), bg)
107
+ y = gap
108
+ for row, h in zip(rows, heights):
109
+ h = int(round(h)); x = gap
110
+ for im in row:
111
+ w = max(1, round(h * im.width / im.height))
112
+ canvas.paste(im.resize((w, h)), (x, y))
113
+ x += w + gap
114
+ y += h + gap
115
+ return canvas.crop((0, 0, W, Ht))
116
+
117
+
118
+ def main():
119
+ ap = argparse.ArgumentParser()
120
+ ap.add_argument("--exclude", default="", help="comma-separated indices to drop")
121
+ ap.add_argument("--n_show", type=int, default=0, help="render only first N picks (0=all kept)")
122
+ ap.add_argument("--n_collage", type=int, default=0, help="use N panels for collage (0=all)")
123
+ ap.add_argument("--out", default=os.path.join(ROOT, "imagenet1k_camera_map_gallery.png"))
124
+ ap.add_argument("--target_w", type=int, default=3400)
125
+ ap.add_argument("--ratio", default="4:3", help='collage aspect W:H, e.g. 4:3, 1:1, 16:9')
126
+ args = ap.parse_args()
127
+ rw, rh = (int(x) for x in args.ratio.split(":"))
128
+
129
+ excl = set(int(x) for x in args.exclude.split(",") if x.strip() != "")
130
+ meta = [m for m in json.load(open(PICKS)) if m["idx"] not in excl]
131
+ if args.n_show:
132
+ meta = meta[:args.n_show]
133
+ print(f"rendering {len(meta)} panels ...")
134
+
135
+ mega = os.environ.get("GALLERY_DATASET") == "megalith"
136
+ imgs = {} if mega else (print("loading source images ...") or G.load_source_images(8))
137
+ items = []
138
+ for m in meta:
139
+ b = G.fetch_url(m["url"]) if mega else imgs.get(m["val"])
140
+ if not b:
141
+ continue
142
+ try:
143
+ pil = Image.open(io.BytesIO(b)).convert("RGB")
144
+ except Exception:
145
+ continue
146
+ items.append(render_nopad(pil, m["roll"], m["pitch"], m["vfov"], 0.0))
147
+ print(f"rendered {len(items)} panels")
148
+
149
+ # optionally pick N_collage of them spread across aspect ratio for variety
150
+ if args.n_collage and args.n_collage < len(items):
151
+ order = sorted(range(len(items)), key=lambda i: items[i].width / items[i].height)
152
+ step = len(order) / args.n_collage
153
+ sel = sorted(order[int(k * step)] for k in range(args.n_collage))
154
+ items = [items[i] for i in sel]
155
+ print(f"selected {len(items)} for collage (aspect-spread)")
156
+
157
+ col = aspect_collage(items, W=args.target_w, ratio=(rw, rh))
158
+ col.save(args.out)
159
+ print("saved collage ->", args.out, col.size)
160
+
161
+
162
+ if __name__ == "__main__":
163
+ main()