"""Camera-map gallery for ImageNet-1K-Camera. For N diverse samples: take the predicted (roll,pitch,vfov,k1) from KangLiao/ImageNet-1K-Camera (val split), fetch the matching source image from ILSVRC/imagenet-1k (val parquets), compute the up-field & latitude-field (perspective fields, same as scripts/camera/cam_dataset_debug.py) and render them overlaid on the image, side by side. All samples are tiled into one gallery PNG. """ import argparse import io import json import os import re import tarfile import numpy as np import torch from PIL import Image, ImageDraw, ImageFont import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from huggingface_hub import hf_hub_download import pyarrow.parquet as pq from scripts.camera.geometry.camera import SimpleRadial from scripts.camera.geometry.gravity import Gravity from scripts.camera.geometry.perspective_fields import get_perspective_field from scripts.camera.utils.conversions import fov2focal from scripts.camera.visualization.viz2d import plot_vector_fields, plot_latitudes CACHE = "/tmp/gallery" DEG = 180.0 / np.pi DATASET = os.environ.get("GALLERY_DATASET", "imagenet") # ---- ImageNet (val split; key = ILSVRC val number) -------------------------- def _cap_imagenet(): p = hf_hub_download("KangLiao/ImageNet-1K-Camera", "val.tar", repo_type="dataset", local_dir=os.path.join(CACHE, "in_cap")) caps = {} with tarfile.open(p) as t: for m in t.getmembers(): if m.name.endswith(".json"): d = json.loads(t.extractfile(m).read()) num = re.search(r"val_(\d+)", m.name) if num and d.get("parse_ok", False): caps[int(num.group(1))] = d return caps def _src_imagenet(n_parquets): imgs = {} for i in range(n_parquets): p = hf_hub_download("ILSVRC/imagenet-1k", f"data/validation-{i:05d}-of-00014.parquet", repo_type="dataset", local_dir=os.path.join(CACHE, "in_src")) pf = pq.ParquetFile(p) for rg in range(pf.num_row_groups): for img in pf.read_row_group(rg, columns=["image"]).to_pydict()["image"]: num = re.search(r"val_(\d+)", img["path"]) if num and img.get("bytes"): imgs[int(num.group(1))] = img["bytes"] return imgs # ---- COCO (val split; key = COCO image_id) ---------------------------------- def _cap_coco(): from huggingface_hub import HfApi caps = {} for f in [x for x in HfApi().list_repo_files("KangLiao/COCO-Camera", repo_type="dataset") if "coco_val_" in x and x.endswith(".tar")]: p = hf_hub_download("KangLiao/COCO-Camera", f, repo_type="dataset", local_dir=os.path.join(CACHE, "coco_cap")) with tarfile.open(p) as t: for m in t.getmembers(): if m.name.endswith(".json"): d = json.loads(t.extractfile(m).read()) if d.get("parse_ok", False): caps[int(os.path.basename(m.name)[:-5])] = d return caps def _src_coco(n_parquets): from huggingface_hub import HfApi vals = sorted(x for x in HfApi().list_repo_files("detection-datasets/coco", repo_type="dataset") if os.path.basename(x).startswith("val-") and x.endswith(".parquet")) imgs = {} for f in vals[:max(n_parquets, 2)]: p = hf_hub_download("detection-datasets/coco", f, repo_type="dataset", local_dir=os.path.join(CACHE, "coco_src")) pf = pq.ParquetFile(p) for rg in range(pf.num_row_groups): t = pf.read_row_group(rg, columns=["image_id", "image"]).to_pydict() for iid, img in zip(t["image_id"], t["image"]): if img.get("bytes"): imgs[int(iid)] = img["bytes"] return imgs # ---- CC12M (key = "/"; source = pixparse/cc12m-wds) ----------- CC12M_SHARDS = list(range(6)) # which shards to sample from (limits download) def _cap_cc12m(): caps = {} for s in CC12M_SHARDS: p = hf_hub_download("KangLiao/CC12M-Camera", f"{s:04d}.tar", repo_type="dataset", local_dir=os.path.join(CACHE, "cc12m_cap")) with tarfile.open(p) as t: for m in t.getmembers(): if m.name.endswith(".json"): d = json.loads(t.extractfile(m).read()) if d.get("parse_ok", False): caps[f"{s:04d}/{os.path.basename(m.name)[:-5]}"] = d return caps def _src_cc12m(_n): imgs = {} for s in CC12M_SHARDS: p = hf_hub_download("pixparse/cc12m-wds", f"cc12m-train-{s:04d}.tar", repo_type="dataset", local_dir=os.path.join(CACHE, "cc12m_src")) with tarfile.open(p) as t: for m in t.getmembers(): if m.name.endswith(".jpg"): imgs[f"{s:04d}/{os.path.basename(m.name)[:-4]}"] = t.extractfile(m).read() return imgs # ---- Megalith (caption carries `url`; source fetched from that url) --------- MEGALITH_SHARDS = list(range(6)) def _cap_megalith(): caps = {} for s in MEGALITH_SHARDS: p = hf_hub_download("KangLiao/Megalith-10M-Camera", f"{s:05d}.tar", repo_type="dataset", local_dir=os.path.join(CACHE, "mega_cap")) with tarfile.open(p) as t: for m in t.getmembers(): if m.name.endswith(".json"): d = json.loads(t.extractfile(m).read()) if d.get("parse_ok", False) and d.get("url"): caps[f"{s:05d}/{os.path.basename(m.name)[:-5]}"] = d return caps def fetch_url(url, timeout=12): """Download bytes from a URL, bypassing the (flaky) env proxy. None on fail.""" import requests try: r = requests.get(url, timeout=timeout, proxies={"http": None, "https": None}) r.raise_for_status() return r.content except Exception: return None def load_captions(): return {"coco": _cap_coco, "cc12m": _cap_cc12m, "megalith": _cap_megalith}.get(DATASET, _cap_imagenet)() def load_source_images(n_parquets): # megalith fetches per-selected-sample via fetch_url (handled by callers) return {"coco": _src_coco, "cc12m": _src_cc12m}.get(DATASET, _src_imagenet)(n_parquets) def select_diverse(candidates, n): """Farthest-point sampling in (roll,pitch,vfov) degree space -> diversity, guaranteed to include non-trivial (non-zero) roll/pitch/fov extremes.""" keys = list(candidates) X = np.array([[candidates[k]["roll"] * DEG, candidates[k]["pitch"] * DEG, candidates[k]["vfov"] * DEG] for k in keys], dtype=np.float64) Xn = (X - X.mean(0)) / (X.std(0) + 1e-6) # seed: the most extreme sample (largest deviation from mean) seed = int(np.argmax((Xn ** 2).sum(1))) chosen = [seed] d = np.linalg.norm(Xn - Xn[seed], axis=1) while len(chosen) < min(n, len(keys)): nxt = int(np.argmax(d)) chosen.append(nxt) d = np.minimum(d, np.linalg.norm(Xn - Xn[nxt], axis=1)) return [keys[i] for i in chosen] def prep_image(pil, size=640): w, h = pil.size if w >= h: nw, nh = size, max(1, round(h * size / w)) else: nh, nw = size, max(1, round(w * size / h)) pil = pil.resize((nw, nh)) canvas = Image.new("RGB", (size, size), (0, 0, 0)) canvas.paste(pil, ((size - nw) // 2, (size - nh) // 2)) return canvas def compute_fields(roll, pitch, vfov, k1, h=640, w=640): f = fov2focal(torch.tensor(float(vfov)), h) params = torch.tensor([w, h, float(f), float(f), w / 2, h / 2, float(k1), 0]).float() cam = SimpleRadial(params).float() grav = Gravity.from_rp(torch.tensor(float(roll)), torch.tensor(float(pitch))) up, lat = get_perspective_field(cam, grav, use_up=True, use_latitude=True) return up[0], lat[0] # up (2,H,W), lat (1,H,W) def render_pair(img640, up_field, lat_field, panel_px=380): """One sample -> a [up | lat] RGB image (numpy).""" imnp = np.asarray(img640).astype(np.float32) / 255.0 fig, axes = plt.subplots(1, 2, figsize=(2 * panel_px / 100, panel_px / 100), dpi=100) for ax in axes: ax.imshow(imnp) ax.set_axis_off() ax.set_xlim([0, 640]); ax.set_ylim([640, 0]) plot_vector_fields([up_field], axes=[axes[0]]) lat_deg = (lat_field[0] * DEG) plot_latitudes([lat_deg], is_radians=False, axes=[axes[1]]) axes[0].set_title("up field", fontsize=11) axes[1].set_title("latitude field", fontsize=11) fig.subplots_adjust(left=0, right=1, top=0.93, bottom=0, wspace=0.02) fig.canvas.draw() buf = np.asarray(fig.canvas.buffer_rgba())[..., :3].copy() plt.close(fig) return buf def build_gallery(panels, params, ncols, out_path): ph, pw = panels[0].shape[:2] gap, top = 16, 90 cap_h = 30 cell_h = ph + cap_h nrows = (len(panels) + ncols - 1) // ncols W = ncols * pw + (ncols + 1) * gap H = top + nrows * (cell_h + gap) + gap canvas = Image.new("RGB", (W, H), (245, 246, 248)) draw = ImageDraw.Draw(canvas) try: ft = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 40) fs = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 16) except Exception: ft = ImageFont.load_default(); fs = ImageFont.load_default() draw.text((gap, 26), "ImageNet-1K-Camera — Camera-Map Gallery (up & latitude fields)", fill=(30, 30, 40), font=ft) for i, (pan, pr) in enumerate(zip(panels, params)): r, c = divmod(i, ncols) x = gap + c * (pw + gap) y = top + r * (cell_h + gap) canvas.paste(Image.fromarray(pan), (x, y)) txt = (f"roll {pr['roll']*DEG:+.1f}° pitch {pr['pitch']*DEG:+.1f}° " f"fov {pr['vfov']*DEG:.1f}°") draw.text((x + 6, y + ph + 6), txt, fill=(60, 60, 70), font=fs) canvas.save(out_path) print("saved gallery ->", out_path, canvas.size) def main(): ap = argparse.ArgumentParser() ap.add_argument("--n", type=int, default=50) ap.add_argument("--ncols", type=int, default=5) ap.add_argument("--parquets", type=int, default=6) ap.add_argument("--out", default="output/imagenet1k_camera_map_gallery.png") args = ap.parse_args() print("loading captions ..."); caps = load_captions() print("loading source images ..."); imgs = load_source_images(args.parquets) cand = {k: caps[k] for k in caps if k in imgs} print(f"candidates with both caption+image: {len(cand)}") picks = select_diverse(cand, args.n) print(f"selected {len(picks)} diverse samples") panels, params = [], [] for k in picks: pr = cand[k] pil = Image.open(io.BytesIO(imgs[k])).convert("RGB") img640 = prep_image(pil) up, lat = compute_fields(pr["roll"], pr["pitch"], pr["vfov"], pr["k1"]) panels.append(render_pair(img640, up, lat)) params.append(pr) os.makedirs(os.path.dirname(args.out) or ".", exist_ok=True) build_gallery(panels, params, args.ncols, args.out) # report the diversity actually achieved rs = np.array([p["roll"] * DEG for p in params]) ps = np.array([p["pitch"] * DEG for p in params]) vs = np.array([p["vfov"] * DEG for p in params]) print(f"roll range [{rs.min():.1f},{rs.max():.1f}] std {rs.std():.1f}") print(f"pitch range [{ps.min():.1f},{ps.max():.1f}] std {ps.std():.1f}") print(f"fov range [{vs.min():.1f},{vs.max():.1f}] std {vs.std():.1f}") if __name__ == "__main__": main()