Delete analysis/camera_map_skill
Browse files
analysis/camera_map_skill/SKILL.md
DELETED
|
@@ -1,83 +0,0 @@
|
|
| 1 |
-
---
|
| 2 |
-
name: camera-map-gallery
|
| 3 |
-
description: >
|
| 4 |
-
Build an interactive camera-map review gallery for a Camera dataset and
|
| 5 |
-
compose a final collage. Invoke when the user gives a command shaped like
|
| 6 |
-
"<dataset> + (A, B) + C [+ W:H]" (e.g. "ImageNet-1K + (80, 30) + 40 + 4:3"),
|
| 7 |
-
or asks to visualize/gallery/collage predicted camera parameters (up field /
|
| 8 |
-
latitude field) with a web review step.
|
| 9 |
-
---
|
| 10 |
-
|
| 11 |
-
# Camera-Map Gallery & Collage
|
| 12 |
-
|
| 13 |
-
## Command format
|
| 14 |
-
```
|
| 15 |
-
<dataset> + (A, B) + C [+ W:H]
|
| 16 |
-
```
|
| 17 |
-
- `dataset` — which Camera dataset (picks HF caption repo + source-image repo)
|
| 18 |
-
- `A` — # large-offset samples (farthest-point sampling over roll/pitch/fov)
|
| 19 |
-
- `B` — # random samples (no camera-param range restriction)
|
| 20 |
-
- `C` — # panels in the final collage (dynamic: pick ~C from the kept results)
|
| 21 |
-
- `W:H` — collage aspect ratio, default `4:3`
|
| 22 |
-
|
| 23 |
-
## Pipeline (run in the puffin env, cwd = repo root, `PYTHONPATH=./`)
|
| 24 |
-
Env: `/data/NTU_slab/kliao/envs/puffin/bin/python`
|
| 25 |
-
|
| 26 |
-
1. **Review page** — `build_review.py --n_diverse A --n_random B`
|
| 27 |
-
Samples A diverse + B random camera params, matches source images, renders
|
| 28 |
-
each as `up | latitude` (native aspect, NO padding, NO text), writes a
|
| 29 |
-
self-contained interactive HTML to `output/gallery_review.html`
|
| 30 |
-
(index badges + per-sample "剔除" checkbox + submit -> `EXCLUDE=[...]` code).
|
| 31 |
-
Persists `output/gallery_picks.json` (ordered val ids + params) and
|
| 32 |
-
`output/gallery_panels/`.
|
| 33 |
-
2. **Publish link** — upload `output/gallery_review.html` as `index.html` to a
|
| 34 |
-
HF **static Space** (`KangLiao/imagenet-camera-review`); give the user the
|
| 35 |
-
public URL. They review, submit, and paste back the `EXCLUDE=[...]` code.
|
| 36 |
-
3. **Collage** — `make_collage.py --exclude "3,9,..." --n_collage C
|
| 37 |
-
--target_w 3600 --ratio W:H --out output/<dataset>_camera_map_collage.png`
|
| 38 |
-
Drops excluded, dynamically takes ~C by aspect spread, renders no-pad panels,
|
| 39 |
-
composes a **balanced-rows** collage at exactly W:H (filled, no whitespace,
|
| 40 |
-
no black frames), then upload to the dataset's HF Camera repo under
|
| 41 |
-
`analysis/`.
|
| 42 |
-
|
| 43 |
-
## Field computation (reused, do NOT reinvent)
|
| 44 |
-
`gallery_lib.compute_fields(roll,pitch,vfov,k1)` -> up (2,H,W) + latitude (1,H,W)
|
| 45 |
-
via `scripts/camera` geometry (SimpleRadial + Gravity + get_perspective_field),
|
| 46 |
-
same pipeline as `scripts/camera/cam_dataset_debug.py`. No-pad render crops the
|
| 47 |
-
640x640 field back to the un-padded region so it aligns with the native image.
|
| 48 |
-
|
| 49 |
-
## Per-dataset sources
|
| 50 |
-
| dataset | caption repo | source images |
|
| 51 |
-
|---------|--------------|----------------|
|
| 52 |
-
| ImageNet-1K | KangLiao/ImageNet-1K-Camera | ILSVRC/imagenet-1k (val, match by filename) |
|
| 53 |
-
| COCO | KangLiao/COCO-Camera | detection-datasets/coco (embedded) |
|
| 54 |
-
| CC12M / Megalith | KangLiao/{CC12M,Megalith-10M}-Camera | `url` field in each caption json |
|
| 55 |
-
| gpic | (tbd) | local tar shards |
|
| 56 |
-
|
| 57 |
-
`gallery_lib.py` currently implements the ImageNet-1K loaders; other datasets
|
| 58 |
-
reuse the same select_diverse / prep_image / compute_fields, swap the two
|
| 59 |
-
loaders (caption repo + source fetch).
|
| 60 |
-
|
| 61 |
-
## Notes
|
| 62 |
-
- Diversity uses farthest-point sampling so orientations span the full range.
|
| 63 |
-
- The whole review page is client-side (static Space = no backend), so the
|
| 64 |
-
user's selection only comes back via the copyable `EXCLUDE=[...]` code.
|
| 65 |
-
- `gallery_picks.json` lets the collage be reproduced exactly from that code.
|
| 66 |
-
|
| 67 |
-
## Running elsewhere / adding DL3DV
|
| 68 |
-
Portable: put `gallery_lib.py`, `build_review.py`, `make_collage.py` together and
|
| 69 |
-
run `build_review.py` / `make_collage.py` with the Puffin repo on `PYTHONPATH`
|
| 70 |
-
(they need `scripts/camera/*` for the field geometry). Pick the dataset with the
|
| 71 |
-
env var `GALLERY_DATASET`.
|
| 72 |
-
|
| 73 |
-
To add **DL3DV** (images on AOSS, GT camera captions on disk), add two loaders in
|
| 74 |
-
`gallery_lib.py` and a `"dl3dv"` dispatch entry — mirror the existing ones:
|
| 75 |
-
- `_cap_dl3dv()` → read `<camera_caption_root>/<scene>/dense/camera/frame_XXXXX.json`
|
| 76 |
-
(roll/pitch/vfov/k1); key = `"<scene>/<frame>"`.
|
| 77 |
-
- `_src_dl3dv()` → read the RGB frame from AOSS
|
| 78 |
-
(`<ROOT>/<scene>/dense/rgb/frame_XXXXX.png`) via `aoss_client` /
|
| 79 |
-
`src/dust3r/oss_file_client.FileClient` (needs `~/aoss.conf`). To avoid the big
|
| 80 |
-
`cache_path` index, list/select scenes directly, then fetch only the picked
|
| 81 |
-
frames' RGB by key (no full-dataset indexing needed).
|
| 82 |
-
Config reference: `configs/datasets/multi_view/gen_dl3dv.py`
|
| 83 |
-
(`ROOT` = aoss s3 prefix, `camera_caption_root` = GT captions).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
analysis/camera_map_skill/build_review.py
DELETED
|
@@ -1,183 +0,0 @@
|
|
| 1 |
-
"""Interactive review page (v2) for the ImageNet camera-map gallery.
|
| 2 |
-
|
| 3 |
-
100 samples = 80 diverse (farthest-point in roll/pitch/fov) + 20 uniformly
|
| 4 |
-
random (no range restriction). Each panel shows [up | latitude] (no text) with a
|
| 5 |
-
visible index badge and an "exclude" checkbox. Submit -> composes the kept panels
|
| 6 |
-
into a final gallery (no text, downloadable) AND prints a copyable EXCLUDE code.
|
| 7 |
-
|
| 8 |
-
Also persists the panels (output/gallery_panels/panel_XXX.png) and the ordered
|
| 9 |
-
sample list (output/gallery_picks.json) so the final gallery can be reproduced
|
| 10 |
-
server-side from the user's EXCLUDE code and uploaded to HF.
|
| 11 |
-
"""
|
| 12 |
-
import base64
|
| 13 |
-
import io
|
| 14 |
-
import json
|
| 15 |
-
import os
|
| 16 |
-
import random
|
| 17 |
-
import sys
|
| 18 |
-
|
| 19 |
-
import numpy as np
|
| 20 |
-
from PIL import Image
|
| 21 |
-
|
| 22 |
-
import os as _os; sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
|
| 23 |
-
import gallery_lib as G
|
| 24 |
-
|
| 25 |
-
import argparse
|
| 26 |
-
_ap = argparse.ArgumentParser()
|
| 27 |
-
_ap.add_argument("--n_diverse", type=int, default=80)
|
| 28 |
-
_ap.add_argument("--n_random", type=int, default=20)
|
| 29 |
-
_args, _ = _ap.parse_known_args()
|
| 30 |
-
N_DIVERSE = _args.n_diverse
|
| 31 |
-
N_RANDOM = _args.n_random
|
| 32 |
-
NCOLS_FINAL = 4
|
| 33 |
-
ROOT = "/data/NTU_slab/kliao/code/Puffin_Final/Puffin2/output"
|
| 34 |
-
PANEL_DIR = os.path.join(ROOT, "gallery_panels")
|
| 35 |
-
PICKS_JSON = os.path.join(ROOT, "gallery_picks.json")
|
| 36 |
-
OUT_HTML = os.path.join(ROOT, "gallery_review.html")
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
def render_pair_notext(img640, up_field, lat_field, panel_px=340):
|
| 40 |
-
import matplotlib
|
| 41 |
-
matplotlib.use("Agg")
|
| 42 |
-
import matplotlib.pyplot as plt
|
| 43 |
-
from scripts.camera.visualization.viz2d import plot_vector_fields, plot_latitudes
|
| 44 |
-
imnp = np.asarray(img640).astype(np.float32) / 255.0
|
| 45 |
-
fig, axes = plt.subplots(1, 2, figsize=(2 * panel_px / 100, panel_px / 100), dpi=100)
|
| 46 |
-
for ax in axes:
|
| 47 |
-
ax.imshow(imnp); ax.set_axis_off()
|
| 48 |
-
ax.set_xlim([0, 640]); ax.set_ylim([640, 0])
|
| 49 |
-
plot_vector_fields([up_field], axes=[axes[0]])
|
| 50 |
-
plot_latitudes([lat_field[0] * G.DEG], is_radians=False, axes=[axes[1]])
|
| 51 |
-
fig.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0.01)
|
| 52 |
-
fig.canvas.draw()
|
| 53 |
-
buf = np.asarray(fig.canvas.buffer_rgba())[..., :3].copy()
|
| 54 |
-
plt.close(fig)
|
| 55 |
-
return buf
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
def b64jpg(arr, q=85):
|
| 59 |
-
im = Image.fromarray(arr); b = io.BytesIO(); im.save(b, "JPEG", quality=q)
|
| 60 |
-
return base64.b64encode(b.getvalue()).decode()
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
def main():
|
| 64 |
-
print("loading captions ..."); caps = G.load_captions()
|
| 65 |
-
if os.environ.get("GALLERY_DATASET") == "megalith":
|
| 66 |
-
# url mode: select from captions, then download only the picks (with
|
| 67 |
-
# oversampling to tolerate dead Flickr links).
|
| 68 |
-
from concurrent.futures import ThreadPoolExecutor
|
| 69 |
-
cand = caps
|
| 70 |
-
div_pool = G.select_diverse(cand, min(len(cand), N_DIVERSE * 2))
|
| 71 |
-
rest = [k for k in cand if k not in set(div_pool)]
|
| 72 |
-
random.seed(1234)
|
| 73 |
-
rnd_pool = random.sample(rest, min(len(rest), N_RANDOM * 3))
|
| 74 |
-
imgs, picks, kinds = {}, [], []
|
| 75 |
-
_f = lambda k: (k, G.fetch_url(cand[k]["url"]))
|
| 76 |
-
with ThreadPoolExecutor(max_workers=32) as ex:
|
| 77 |
-
for k, b in ex.map(_f, div_pool):
|
| 78 |
-
if b:
|
| 79 |
-
imgs[k] = b; picks.append(k); kinds.append("diverse")
|
| 80 |
-
if kinds.count("diverse") >= N_DIVERSE: break
|
| 81 |
-
for k, b in ex.map(_f, rnd_pool):
|
| 82 |
-
if b:
|
| 83 |
-
imgs[k] = b; picks.append(k); kinds.append("random")
|
| 84 |
-
if kinds.count("random") >= N_RANDOM: break
|
| 85 |
-
print(f"picks: {len(picks)} ({kinds.count('diverse')} div + {kinds.count('random')} rnd, downloaded)")
|
| 86 |
-
else:
|
| 87 |
-
print("loading source images ..."); imgs = G.load_source_images(8)
|
| 88 |
-
cand = {k: caps[k] for k in caps if k in imgs}
|
| 89 |
-
print(f"candidates: {len(cand)}")
|
| 90 |
-
diverse = G.select_diverse(cand, N_DIVERSE)
|
| 91 |
-
rest = [k for k in cand if k not in set(diverse)]
|
| 92 |
-
random.seed(1234)
|
| 93 |
-
rnd = random.sample(rest, N_RANDOM)
|
| 94 |
-
picks = diverse + rnd
|
| 95 |
-
kinds = ["diverse"] * len(diverse) + ["random"] * len(rnd)
|
| 96 |
-
print(f"picks: {len(picks)} ({len(diverse)} diverse + {len(rnd)} random)")
|
| 97 |
-
|
| 98 |
-
os.makedirs(PANEL_DIR, exist_ok=True)
|
| 99 |
-
b64s, meta = [], []
|
| 100 |
-
for i, k in enumerate(picks):
|
| 101 |
-
pr = cand[k]
|
| 102 |
-
pil = Image.open(io.BytesIO(imgs[k])).convert("RGB")
|
| 103 |
-
img640 = G.prep_image(pil)
|
| 104 |
-
up, lat = G.compute_fields(pr["roll"], pr["pitch"], pr["vfov"], pr["k1"])
|
| 105 |
-
arr = render_pair_notext(img640, up, lat)
|
| 106 |
-
Image.fromarray(arr).save(os.path.join(PANEL_DIR, f"panel_{i:03d}.png"))
|
| 107 |
-
b64s.append(b64jpg(arr))
|
| 108 |
-
meta.append({"idx": i, "val": k, "kind": kinds[i], "url": pr.get("url"),
|
| 109 |
-
"roll": pr["roll"], "pitch": pr["pitch"], "vfov": pr["vfov"]})
|
| 110 |
-
if (i + 1) % 25 == 0:
|
| 111 |
-
print(f" {i+1}/{len(picks)}")
|
| 112 |
-
json.dump(meta, open(PICKS_JSON, "w"))
|
| 113 |
-
print("saved picks ->", PICKS_JSON, "panels ->", PANEL_DIR)
|
| 114 |
-
|
| 115 |
-
cells = "\n".join(
|
| 116 |
-
f'<div class="cell" id="c{i}"><div class="idx">#{i}'
|
| 117 |
-
f'{" · rand" if kinds[i]=="random" else ""}</div>'
|
| 118 |
-
f'<img class="pan" data-idx="{i}" src="data:image/jpeg;base64,{b}">'
|
| 119 |
-
f'<label class="ex"><input type="checkbox" class="excl" data-idx="{i}"> 剔除</label></div>'
|
| 120 |
-
for i, b in enumerate(b64s))
|
| 121 |
-
|
| 122 |
-
html = f"""<!doctype html><html lang="zh"><head><meta charset="utf-8">
|
| 123 |
-
<title>ImageNet Camera-Map Review</title><style>
|
| 124 |
-
body{{font-family:system-ui,Arial,sans-serif;margin:16px;background:#f5f6f8;color:#222}}
|
| 125 |
-
h2{{margin:6px 0}} .hint{{color:#555;margin-bottom:8px;font-size:14px}}
|
| 126 |
-
#grid{{display:grid;grid-template-columns:repeat(2,1fr);gap:14px}}
|
| 127 |
-
.cell{{position:relative;background:#fff;border:1px solid #e2e4e8;border-radius:8px;
|
| 128 |
-
padding:8px;display:flex;align-items:center;gap:10px}}
|
| 129 |
-
.cell img{{width:100%;max-width:680px;border-radius:6px;display:block}}
|
| 130 |
-
.idx{{position:absolute;top:10px;left:10px;background:rgba(0,0,0,.6);color:#fff;
|
| 131 |
-
font-size:12px;padding:1px 6px;border-radius:5px}}
|
| 132 |
-
.ex{{white-space:nowrap;font-size:15px;user-select:none}}
|
| 133 |
-
.cell.dropped{{opacity:.35;outline:2px solid #e05353}}
|
| 134 |
-
.bar{{position:sticky;top:0;background:#f5f6f8;padding:10px 0;z-index:5;border-bottom:1px solid #ddd}}
|
| 135 |
-
button{{font-size:16px;padding:8px 18px;border-radius:8px;border:0;background:#2d6cdf;color:#fff;cursor:pointer}}
|
| 136 |
-
textarea{{width:100%;height:60px;font-family:monospace;font-size:13px;margin-top:8px}}
|
| 137 |
-
#result{{margin-top:16px}} #result img{{max-width:100%;border:1px solid #ccc}}
|
| 138 |
-
</style></head><body>
|
| 139 |
-
<div class="bar">
|
| 140 |
-
<h2>ImageNet-1K 相机地图审核(共 {len(b64s)} 个 = 80 多样 + 20 随机)</h2>
|
| 141 |
-
<div class="hint">勾选「剔除」以移除该样本;左=up field,右=latitude field;标 rand 的是随机样本。
|
| 142 |
-
点提交后:下方给出①最终 gallery 下载 ②可复制的剔除代码——把代码贴给对方即可。</div>
|
| 143 |
-
<button onclick="compose()">提交(生成最终 gallery + 剔除代码)</button>
|
| 144 |
-
<span id="cnt"></span>
|
| 145 |
-
</div>
|
| 146 |
-
<div id="grid">
|
| 147 |
-
{cells}
|
| 148 |
-
</div>
|
| 149 |
-
<div id="result"></div>
|
| 150 |
-
<script>
|
| 151 |
-
const TOTAL={len(b64s)}, NCOLS={NCOLS_FINAL};
|
| 152 |
-
document.querySelectorAll('.excl').forEach(cb=>cb.addEventListener('change',e=>{{
|
| 153 |
-
e.target.closest('.cell').classList.toggle('dropped',e.target.checked); upd();}}));
|
| 154 |
-
function upd(){{const ex=[...document.querySelectorAll('.excl')].filter(c=>c.checked).length;
|
| 155 |
-
document.getElementById('cnt').textContent=' 已剔除 '+ex+' / 保留 '+(TOTAL-ex);}}
|
| 156 |
-
upd();
|
| 157 |
-
function compose(){{
|
| 158 |
-
const excl=[...document.querySelectorAll('.excl')].filter(c=>c.checked).map(c=>+c.dataset.idx).sort((a,b)=>a-b);
|
| 159 |
-
const kept=[...document.querySelectorAll('.pan')].filter(img=>!excl.includes(+img.dataset.idx));
|
| 160 |
-
if(!kept.length){{alert('全部被剔除了');return;}}
|
| 161 |
-
const pw=kept[0].naturalWidth, ph=kept[0].naturalHeight, gap=10;
|
| 162 |
-
const rows=Math.ceil(kept.length/NCOLS), W=NCOLS*pw+(NCOLS+1)*gap, H=rows*ph+(rows+1)*gap;
|
| 163 |
-
const cv=document.createElement('canvas'); cv.width=W; cv.height=H;
|
| 164 |
-
const ctx=cv.getContext('2d'); ctx.fillStyle='#f5f6f8'; ctx.fillRect(0,0,W,H);
|
| 165 |
-
kept.forEach((img,k)=>{{const r=Math.floor(k/NCOLS),c=k%NCOLS;
|
| 166 |
-
ctx.drawImage(img,gap+c*(pw+gap),gap+r*(ph+gap),pw,ph);}});
|
| 167 |
-
const url=cv.toDataURL('image/png');
|
| 168 |
-
const code='EXCLUDE='+JSON.stringify(excl);
|
| 169 |
-
document.getElementById('result').innerHTML=
|
| 170 |
-
'<h3>最终 gallery:保留 '+kept.length+' 个(剔除 '+excl.length+')</h3>'+
|
| 171 |
-
'<b>把下面这行剔除代码复制发给对方:</b>'+
|
| 172 |
-
'<textarea readonly onclick="this.select()">'+code+'</textarea>'+
|
| 173 |
-
'<a download="imagenet_camera_gallery_final.png" href="'+url+'">⬇ 下载最终 gallery PNG</a><br><br>'+
|
| 174 |
-
'<img src="'+url+'">';
|
| 175 |
-
document.getElementById('result').scrollIntoView({{behavior:'smooth'}});
|
| 176 |
-
}}
|
| 177 |
-
</script></body></html>"""
|
| 178 |
-
open(OUT_HTML, "w", encoding="utf-8").write(html)
|
| 179 |
-
print("wrote", OUT_HTML, f"({len(html)/1e6:.1f} MB)")
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
if __name__ == "__main__":
|
| 183 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
analysis/camera_map_skill/gallery_lib.py
DELETED
|
@@ -1,294 +0,0 @@
|
|
| 1 |
-
"""Camera-map gallery for ImageNet-1K-Camera.
|
| 2 |
-
|
| 3 |
-
For N diverse samples: take the predicted (roll,pitch,vfov,k1) from
|
| 4 |
-
KangLiao/ImageNet-1K-Camera (val split), fetch the matching source image from
|
| 5 |
-
ILSVRC/imagenet-1k (val parquets), compute the up-field & latitude-field
|
| 6 |
-
(perspective fields, same as scripts/camera/cam_dataset_debug.py) and render
|
| 7 |
-
them overlaid on the image, side by side. All samples are tiled into one
|
| 8 |
-
gallery PNG.
|
| 9 |
-
"""
|
| 10 |
-
import argparse
|
| 11 |
-
import io
|
| 12 |
-
import json
|
| 13 |
-
import os
|
| 14 |
-
import re
|
| 15 |
-
import tarfile
|
| 16 |
-
|
| 17 |
-
import numpy as np
|
| 18 |
-
import torch
|
| 19 |
-
from PIL import Image, ImageDraw, ImageFont
|
| 20 |
-
|
| 21 |
-
import matplotlib
|
| 22 |
-
matplotlib.use("Agg")
|
| 23 |
-
import matplotlib.pyplot as plt
|
| 24 |
-
|
| 25 |
-
from huggingface_hub import hf_hub_download
|
| 26 |
-
import pyarrow.parquet as pq
|
| 27 |
-
|
| 28 |
-
from scripts.camera.geometry.camera import SimpleRadial
|
| 29 |
-
from scripts.camera.geometry.gravity import Gravity
|
| 30 |
-
from scripts.camera.geometry.perspective_fields import get_perspective_field
|
| 31 |
-
from scripts.camera.utils.conversions import fov2focal
|
| 32 |
-
from scripts.camera.visualization.viz2d import plot_vector_fields, plot_latitudes
|
| 33 |
-
|
| 34 |
-
CACHE = "/tmp/gallery"
|
| 35 |
-
DEG = 180.0 / np.pi
|
| 36 |
-
DATASET = os.environ.get("GALLERY_DATASET", "imagenet")
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
# ---- ImageNet (val split; key = ILSVRC val number) --------------------------
|
| 40 |
-
def _cap_imagenet():
|
| 41 |
-
p = hf_hub_download("KangLiao/ImageNet-1K-Camera", "val.tar", repo_type="dataset",
|
| 42 |
-
local_dir=os.path.join(CACHE, "in_cap"))
|
| 43 |
-
caps = {}
|
| 44 |
-
with tarfile.open(p) as t:
|
| 45 |
-
for m in t.getmembers():
|
| 46 |
-
if m.name.endswith(".json"):
|
| 47 |
-
d = json.loads(t.extractfile(m).read())
|
| 48 |
-
num = re.search(r"val_(\d+)", m.name)
|
| 49 |
-
if num and d.get("parse_ok", False):
|
| 50 |
-
caps[int(num.group(1))] = d
|
| 51 |
-
return caps
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
def _src_imagenet(n_parquets):
|
| 55 |
-
imgs = {}
|
| 56 |
-
for i in range(n_parquets):
|
| 57 |
-
p = hf_hub_download("ILSVRC/imagenet-1k", f"data/validation-{i:05d}-of-00014.parquet",
|
| 58 |
-
repo_type="dataset", local_dir=os.path.join(CACHE, "in_src"))
|
| 59 |
-
pf = pq.ParquetFile(p)
|
| 60 |
-
for rg in range(pf.num_row_groups):
|
| 61 |
-
for img in pf.read_row_group(rg, columns=["image"]).to_pydict()["image"]:
|
| 62 |
-
num = re.search(r"val_(\d+)", img["path"])
|
| 63 |
-
if num and img.get("bytes"):
|
| 64 |
-
imgs[int(num.group(1))] = img["bytes"]
|
| 65 |
-
return imgs
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
# ---- COCO (val split; key = COCO image_id) ----------------------------------
|
| 69 |
-
def _cap_coco():
|
| 70 |
-
from huggingface_hub import HfApi
|
| 71 |
-
caps = {}
|
| 72 |
-
for f in [x for x in HfApi().list_repo_files("KangLiao/COCO-Camera", repo_type="dataset")
|
| 73 |
-
if "coco_val_" in x and x.endswith(".tar")]:
|
| 74 |
-
p = hf_hub_download("KangLiao/COCO-Camera", f, repo_type="dataset",
|
| 75 |
-
local_dir=os.path.join(CACHE, "coco_cap"))
|
| 76 |
-
with tarfile.open(p) as t:
|
| 77 |
-
for m in t.getmembers():
|
| 78 |
-
if m.name.endswith(".json"):
|
| 79 |
-
d = json.loads(t.extractfile(m).read())
|
| 80 |
-
if d.get("parse_ok", False):
|
| 81 |
-
caps[int(os.path.basename(m.name)[:-5])] = d
|
| 82 |
-
return caps
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
def _src_coco(n_parquets):
|
| 86 |
-
from huggingface_hub import HfApi
|
| 87 |
-
vals = sorted(x for x in HfApi().list_repo_files("detection-datasets/coco", repo_type="dataset")
|
| 88 |
-
if os.path.basename(x).startswith("val-") and x.endswith(".parquet"))
|
| 89 |
-
imgs = {}
|
| 90 |
-
for f in vals[:max(n_parquets, 2)]:
|
| 91 |
-
p = hf_hub_download("detection-datasets/coco", f, repo_type="dataset",
|
| 92 |
-
local_dir=os.path.join(CACHE, "coco_src"))
|
| 93 |
-
pf = pq.ParquetFile(p)
|
| 94 |
-
for rg in range(pf.num_row_groups):
|
| 95 |
-
t = pf.read_row_group(rg, columns=["image_id", "image"]).to_pydict()
|
| 96 |
-
for iid, img in zip(t["image_id"], t["image"]):
|
| 97 |
-
if img.get("bytes"):
|
| 98 |
-
imgs[int(iid)] = img["bytes"]
|
| 99 |
-
return imgs
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
# ---- CC12M (key = "<shard>/<index>"; source = pixparse/cc12m-wds) -----------
|
| 103 |
-
CC12M_SHARDS = list(range(6)) # which shards to sample from (limits download)
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
def _cap_cc12m():
|
| 107 |
-
caps = {}
|
| 108 |
-
for s in CC12M_SHARDS:
|
| 109 |
-
p = hf_hub_download("KangLiao/CC12M-Camera", f"{s:04d}.tar", repo_type="dataset",
|
| 110 |
-
local_dir=os.path.join(CACHE, "cc12m_cap"))
|
| 111 |
-
with tarfile.open(p) as t:
|
| 112 |
-
for m in t.getmembers():
|
| 113 |
-
if m.name.endswith(".json"):
|
| 114 |
-
d = json.loads(t.extractfile(m).read())
|
| 115 |
-
if d.get("parse_ok", False):
|
| 116 |
-
caps[f"{s:04d}/{os.path.basename(m.name)[:-5]}"] = d
|
| 117 |
-
return caps
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
def _src_cc12m(_n):
|
| 121 |
-
imgs = {}
|
| 122 |
-
for s in CC12M_SHARDS:
|
| 123 |
-
p = hf_hub_download("pixparse/cc12m-wds", f"cc12m-train-{s:04d}.tar", repo_type="dataset",
|
| 124 |
-
local_dir=os.path.join(CACHE, "cc12m_src"))
|
| 125 |
-
with tarfile.open(p) as t:
|
| 126 |
-
for m in t.getmembers():
|
| 127 |
-
if m.name.endswith(".jpg"):
|
| 128 |
-
imgs[f"{s:04d}/{os.path.basename(m.name)[:-4]}"] = t.extractfile(m).read()
|
| 129 |
-
return imgs
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
# ---- Megalith (caption carries `url`; source fetched from that url) ---------
|
| 133 |
-
MEGALITH_SHARDS = list(range(6))
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
def _cap_megalith():
|
| 137 |
-
caps = {}
|
| 138 |
-
for s in MEGALITH_SHARDS:
|
| 139 |
-
p = hf_hub_download("KangLiao/Megalith-10M-Camera", f"{s:05d}.tar", repo_type="dataset",
|
| 140 |
-
local_dir=os.path.join(CACHE, "mega_cap"))
|
| 141 |
-
with tarfile.open(p) as t:
|
| 142 |
-
for m in t.getmembers():
|
| 143 |
-
if m.name.endswith(".json"):
|
| 144 |
-
d = json.loads(t.extractfile(m).read())
|
| 145 |
-
if d.get("parse_ok", False) and d.get("url"):
|
| 146 |
-
caps[f"{s:05d}/{os.path.basename(m.name)[:-5]}"] = d
|
| 147 |
-
return caps
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
def fetch_url(url, timeout=12):
|
| 151 |
-
"""Download bytes from a URL, bypassing the (flaky) env proxy. None on fail."""
|
| 152 |
-
import requests
|
| 153 |
-
try:
|
| 154 |
-
r = requests.get(url, timeout=timeout, proxies={"http": None, "https": None})
|
| 155 |
-
r.raise_for_status()
|
| 156 |
-
return r.content
|
| 157 |
-
except Exception:
|
| 158 |
-
return None
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
def load_captions():
|
| 162 |
-
return {"coco": _cap_coco, "cc12m": _cap_cc12m,
|
| 163 |
-
"megalith": _cap_megalith}.get(DATASET, _cap_imagenet)()
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
def load_source_images(n_parquets):
|
| 167 |
-
# megalith fetches per-selected-sample via fetch_url (handled by callers)
|
| 168 |
-
return {"coco": _src_coco, "cc12m": _src_cc12m}.get(DATASET, _src_imagenet)(n_parquets)
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
def select_diverse(candidates, n):
|
| 172 |
-
"""Farthest-point sampling in (roll,pitch,vfov) degree space -> diversity,
|
| 173 |
-
guaranteed to include non-trivial (non-zero) roll/pitch/fov extremes."""
|
| 174 |
-
keys = list(candidates)
|
| 175 |
-
X = np.array([[candidates[k]["roll"] * DEG, candidates[k]["pitch"] * DEG,
|
| 176 |
-
candidates[k]["vfov"] * DEG] for k in keys], dtype=np.float64)
|
| 177 |
-
Xn = (X - X.mean(0)) / (X.std(0) + 1e-6)
|
| 178 |
-
# seed: the most extreme sample (largest deviation from mean)
|
| 179 |
-
seed = int(np.argmax((Xn ** 2).sum(1)))
|
| 180 |
-
chosen = [seed]
|
| 181 |
-
d = np.linalg.norm(Xn - Xn[seed], axis=1)
|
| 182 |
-
while len(chosen) < min(n, len(keys)):
|
| 183 |
-
nxt = int(np.argmax(d))
|
| 184 |
-
chosen.append(nxt)
|
| 185 |
-
d = np.minimum(d, np.linalg.norm(Xn - Xn[nxt], axis=1))
|
| 186 |
-
return [keys[i] for i in chosen]
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
def prep_image(pil, size=640):
|
| 190 |
-
w, h = pil.size
|
| 191 |
-
if w >= h:
|
| 192 |
-
nw, nh = size, max(1, round(h * size / w))
|
| 193 |
-
else:
|
| 194 |
-
nh, nw = size, max(1, round(w * size / h))
|
| 195 |
-
pil = pil.resize((nw, nh))
|
| 196 |
-
canvas = Image.new("RGB", (size, size), (0, 0, 0))
|
| 197 |
-
canvas.paste(pil, ((size - nw) // 2, (size - nh) // 2))
|
| 198 |
-
return canvas
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
def compute_fields(roll, pitch, vfov, k1, h=640, w=640):
|
| 202 |
-
f = fov2focal(torch.tensor(float(vfov)), h)
|
| 203 |
-
params = torch.tensor([w, h, float(f), float(f), w / 2, h / 2, float(k1), 0]).float()
|
| 204 |
-
cam = SimpleRadial(params).float()
|
| 205 |
-
grav = Gravity.from_rp(torch.tensor(float(roll)), torch.tensor(float(pitch)))
|
| 206 |
-
up, lat = get_perspective_field(cam, grav, use_up=True, use_latitude=True)
|
| 207 |
-
return up[0], lat[0] # up (2,H,W), lat (1,H,W)
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
def render_pair(img640, up_field, lat_field, panel_px=380):
|
| 211 |
-
"""One sample -> a [up | lat] RGB image (numpy)."""
|
| 212 |
-
imnp = np.asarray(img640).astype(np.float32) / 255.0
|
| 213 |
-
fig, axes = plt.subplots(1, 2, figsize=(2 * panel_px / 100, panel_px / 100), dpi=100)
|
| 214 |
-
for ax in axes:
|
| 215 |
-
ax.imshow(imnp)
|
| 216 |
-
ax.set_axis_off()
|
| 217 |
-
ax.set_xlim([0, 640]); ax.set_ylim([640, 0])
|
| 218 |
-
plot_vector_fields([up_field], axes=[axes[0]])
|
| 219 |
-
lat_deg = (lat_field[0] * DEG)
|
| 220 |
-
plot_latitudes([lat_deg], is_radians=False, axes=[axes[1]])
|
| 221 |
-
axes[0].set_title("up field", fontsize=11)
|
| 222 |
-
axes[1].set_title("latitude field", fontsize=11)
|
| 223 |
-
fig.subplots_adjust(left=0, right=1, top=0.93, bottom=0, wspace=0.02)
|
| 224 |
-
fig.canvas.draw()
|
| 225 |
-
buf = np.asarray(fig.canvas.buffer_rgba())[..., :3].copy()
|
| 226 |
-
plt.close(fig)
|
| 227 |
-
return buf
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
def build_gallery(panels, params, ncols, out_path):
|
| 231 |
-
ph, pw = panels[0].shape[:2]
|
| 232 |
-
gap, top = 16, 90
|
| 233 |
-
cap_h = 30
|
| 234 |
-
cell_h = ph + cap_h
|
| 235 |
-
nrows = (len(panels) + ncols - 1) // ncols
|
| 236 |
-
W = ncols * pw + (ncols + 1) * gap
|
| 237 |
-
H = top + nrows * (cell_h + gap) + gap
|
| 238 |
-
canvas = Image.new("RGB", (W, H), (245, 246, 248))
|
| 239 |
-
draw = ImageDraw.Draw(canvas)
|
| 240 |
-
try:
|
| 241 |
-
ft = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 40)
|
| 242 |
-
fs = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 16)
|
| 243 |
-
except Exception:
|
| 244 |
-
ft = ImageFont.load_default(); fs = ImageFont.load_default()
|
| 245 |
-
draw.text((gap, 26), "ImageNet-1K-Camera — Camera-Map Gallery (up & latitude fields)",
|
| 246 |
-
fill=(30, 30, 40), font=ft)
|
| 247 |
-
for i, (pan, pr) in enumerate(zip(panels, params)):
|
| 248 |
-
r, c = divmod(i, ncols)
|
| 249 |
-
x = gap + c * (pw + gap)
|
| 250 |
-
y = top + r * (cell_h + gap)
|
| 251 |
-
canvas.paste(Image.fromarray(pan), (x, y))
|
| 252 |
-
txt = (f"roll {pr['roll']*DEG:+.1f}° pitch {pr['pitch']*DEG:+.1f}° "
|
| 253 |
-
f"fov {pr['vfov']*DEG:.1f}°")
|
| 254 |
-
draw.text((x + 6, y + ph + 6), txt, fill=(60, 60, 70), font=fs)
|
| 255 |
-
canvas.save(out_path)
|
| 256 |
-
print("saved gallery ->", out_path, canvas.size)
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
def main():
|
| 260 |
-
ap = argparse.ArgumentParser()
|
| 261 |
-
ap.add_argument("--n", type=int, default=50)
|
| 262 |
-
ap.add_argument("--ncols", type=int, default=5)
|
| 263 |
-
ap.add_argument("--parquets", type=int, default=6)
|
| 264 |
-
ap.add_argument("--out", default="output/imagenet1k_camera_map_gallery.png")
|
| 265 |
-
args = ap.parse_args()
|
| 266 |
-
|
| 267 |
-
print("loading captions ..."); caps = load_captions()
|
| 268 |
-
print("loading source images ..."); imgs = load_source_images(args.parquets)
|
| 269 |
-
cand = {k: caps[k] for k in caps if k in imgs}
|
| 270 |
-
print(f"candidates with both caption+image: {len(cand)}")
|
| 271 |
-
picks = select_diverse(cand, args.n)
|
| 272 |
-
print(f"selected {len(picks)} diverse samples")
|
| 273 |
-
|
| 274 |
-
panels, params = [], []
|
| 275 |
-
for k in picks:
|
| 276 |
-
pr = cand[k]
|
| 277 |
-
pil = Image.open(io.BytesIO(imgs[k])).convert("RGB")
|
| 278 |
-
img640 = prep_image(pil)
|
| 279 |
-
up, lat = compute_fields(pr["roll"], pr["pitch"], pr["vfov"], pr["k1"])
|
| 280 |
-
panels.append(render_pair(img640, up, lat))
|
| 281 |
-
params.append(pr)
|
| 282 |
-
os.makedirs(os.path.dirname(args.out) or ".", exist_ok=True)
|
| 283 |
-
build_gallery(panels, params, args.ncols, args.out)
|
| 284 |
-
# report the diversity actually achieved
|
| 285 |
-
rs = np.array([p["roll"] * DEG for p in params])
|
| 286 |
-
ps = np.array([p["pitch"] * DEG for p in params])
|
| 287 |
-
vs = np.array([p["vfov"] * DEG for p in params])
|
| 288 |
-
print(f"roll range [{rs.min():.1f},{rs.max():.1f}] std {rs.std():.1f}")
|
| 289 |
-
print(f"pitch range [{ps.min():.1f},{ps.max():.1f}] std {ps.std():.1f}")
|
| 290 |
-
print(f"fov range [{vs.min():.1f},{vs.max():.1f}] std {vs.std():.1f}")
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
if __name__ == "__main__":
|
| 294 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
analysis/camera_map_skill/make_collage.py
DELETED
|
@@ -1,163 +0,0 @@
|
|
| 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()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|