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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|