#!/usr/bin/env python3 """Do xem ANH CAMERA co dung duoc de nhan ra cho (VPR) tren robot nay khong. Cau hoi truoc khi dua camera vao relocalization: voi mot anh IR cua D410, tim anh giong nhat trong ban do, anh do co chup o GAN cho nay khong? ============ VI SAO PHAI DO TRUOC ============ Ban ROS (vSLAM_ws) da do tui tu ORB tren hospital: 186/194 lan 0 inlier. D410 chi co anh IR xam, toi (DB robot that 2026-09-25: do sang TB 24/255), trong khi cac mo hinh VPR hoc tren anh MAU. Tot hay te la chua biet -- khong xay truoc khi co so. Mo phong KHONG dung duoc cho viec nay: anh trong DB mo phong DEN HET (bo mo phong chi dung depth bang raycast). ============ CACH CHAM ============ Moi anh hoi: - bo anh trong +-`--excl-sec` giay (cung mot luot di, giong la hien nhien); - anh DUNG = chup trong `--pos-m` met VA lech huong < `--pos-deg` do; - chi CHAM anh hoi co it nhat mot anh dung (cho robot that su quay lai). Chi so: recall@k co anh dung trong k ket qua dau (vi tri + huong) recall@k vi tri chi xet vi tri -- du cho relocalization vi LiDAR tu tim huong khi xac minh recall khi 0 nham nguong cao nhat ma KHONG top-1 sai nao vuot qua, tinh tren MOI anh hoi (ke ca cho chua quay lai -- o do top-1 chac chan sai), con bat duoc bao nhieu anh dung Chay tu goc repo, trong mot moi truong co PyTorch (vd conda training_yolo): python tools/vpr_eval.py --db resources/maps/real_20260925_160449.db Lan dau can internet: torch.hub tai trong so ve ~/.cache/torch/hub. """ import argparse import math import os import sqlite3 import time import zlib import cv2 import numpy as np # ---------------------------------------------------------------- du lieu def mat(blob): return zlib.decompress(blob[:-12]) # 12 byte cuoi = rows, cols, type def load_db(path): c = sqlite3.connect(f"file:{path}?mode=ro", uri=True).cursor() ids_b, poses_b = c.execute("select opt_ids, opt_poses from Admin").fetchone() ids = np.frombuffer(mat(ids_b), dtype=np.int32) P = np.frombuffer(mat(poses_b), dtype=np.float32).reshape(-1, 3, 4) pose = {int(i): P[k] for k, i in enumerate(ids)} stamp = dict(c.execute("select id, stamp from Node").fetchall()) out = [] for nid, blob in c.execute("select id, image from Data where image is not null order by id"): if nid not in pose or nid not in stamp: continue im = cv2.imdecode(np.frombuffer(blob, np.uint8), cv2.IMREAD_GRAYSCALE) if im is None or im.std() < 1e-3: continue # anh den (mo phong) -> vo nghia T = pose[nid] out.append(dict(id=nid, t=float(stamp[nid]), x=float(T[0, 3]), y=float(T[1, 3]), yaw=math.atan2(float(T[1, 0]), float(T[0, 0])), img=im)) return out def clahe(im): return cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(im) def dedot(im): """Xoa van cham cua MAY CHIEU IR tren D410 roi moi tang tuong phan. Mau chieu DI THEO camera, nen tuong gan nao cung phu cung mot van hinh thoi -> cac cho khac nhau trong giong nhau. Do 2026-09-29 (tiny+clahe): cap SAI cach 7.2 m giong 0.74, cao hon moi cap DUNG (0.45-0.69). Trung vi 5x5 dap cham sang don le, Gauss sigma 1.5 lam min phan con lai. """ return clahe(cv2.GaussianBlur(cv2.medianBlur(im, 5), (0, 0), 1.5)) # ---------------------------------------------------------------- mo ta def desc_tiny(imgs): """Moc KHONG hoc: anh 32x24, tru trung binh, chuan hoa -> cosin = NCC.""" D = [] for im in imgs: v = cv2.resize(im, (32, 24), interpolation=cv2.INTER_AREA).astype(np.float32).ravel() v -= v.mean() D.append(v / (np.linalg.norm(v) + 1e-9)) return np.stack(D), 0.0 def torch_desc(model_fn, imgs, size_wh, device, batch=32): """Anh xam -> 3 kenh, chuan hoa ImageNet, chay model_fn theo lo.""" import torch mean = torch.tensor([0.485, 0.456, 0.406], device=device).view(1, 3, 1, 1) std = torch.tensor([0.229, 0.224, 0.225], device=device).view(1, 3, 1, 1) out, t_total = [], 0.0 with torch.no_grad(): for i in range(0, len(imgs), batch): arr = np.stack([cv2.resize(im, size_wh, interpolation=cv2.INTER_LINEAR) for im in imgs[i:i + batch]]).astype(np.float32) / 255.0 x = torch.from_numpy(arr).to(device).unsqueeze(1).repeat(1, 3, 1, 1) x = (x - mean) / std if device.startswith("cuda"): torch.cuda.synchronize() t0 = time.time() d = model_fn(x) if device.startswith("cuda"): torch.cuda.synchronize() t_total += time.time() - t0 d = torch.nn.functional.normalize(d.float(), dim=1) out.append(d.cpu().numpy()) return np.concatenate(out), 1000.0 * t_total / max(1, len(imgs)) def load_models(names, device): """Tra ve {ten: (ham mo ta, (w, h))}. Mo hinh nao tai khong duoc thi bo qua, NOI RO.""" import torch models = {} for name in names: try: if name in ("cosplace", "eigenplaces"): repo = "gmberton/cosplace" if name == "cosplace" else "gmberton/eigenplaces" # skip_validation: KHONG goi API GitHub (khong token thi gioi han # 60 lan/gio -> "403 rate limit exceeded"). Van tai code va # trong so tu github.com nhu thuong. m = torch.hub.load(repo, "get_trained_model", backbone="ResNet50", fc_output_dim=2048, trust_repo=True, skip_validation=True).eval().to(device) # Hoc o 512x512; giu ti le 4:3 cua anh 320x240. models[name] = (lambda x, m=m: m(x), (512, 384)) elif name == "dinov2": m = torch.hub.load("facebookresearch/dinov2", "dinov2_vitb14", trust_repo=True, skip_validation=True).eval().to(device) # Canh phai la boi so cua 14: 448x336 = 32x24 patch. models["dinov2_cls"] = ( lambda x, m=m: m.forward_features(x)["x_norm_clstoken"], (448, 336)) models["dinov2_mean"] = ( lambda x, m=m: m.forward_features(x)["x_norm_patchtokens"].mean(dim=1), (448, 336)) else: print(f" (bo qua mo hinh la: {name})") except Exception as e: # noqa: BLE001 -- noi ro roi di tiep print(f" ⚠️ KHONG TAI DUOC {name}: {e}") return models # ---------------------------------------------------------------- cham def evaluate(D, nodes, excl_sec, pos_m, pos_deg): n = len(nodes) t = np.array([a["t"] for a in nodes]) xy = np.array([[a["x"], a["y"]] for a in nodes]) yaw = np.array([a["yaw"] for a in nodes]) dist = np.linalg.norm(xy[:, None, :] - xy[None, :, :], axis=2) dyaw = np.abs(np.angle(np.exp(1j * (yaw[:, None] - yaw[None, :])))) * 180.0 / math.pi excl = np.abs(t[:, None] - t[None, :]) < excl_sec near = (dist < pos_m) & ~excl pos = near & (dyaw < pos_deg) S = D @ D.T S[excl] = -np.inf order = np.argsort(-S, axis=1) rows = [] for i in range(n): top = order[i, :10] rows.append(dict( i=i, has_pos=bool(pos[i].any()), has_near=bool(near[i].any()), top1=int(top[0]), sim=float(S[i, top[0]]), ok1=bool(pos[i, top[0]]), ok5=bool(pos[i, top[:5]].any()), ok10=bool(pos[i, top].any()), loc1=bool(near[i, top[0]]), loc5=bool(near[i, top[:5]].any()), d1=float(dist[i, top[0]]), dyaw1=float(dyaw[i, top[0]]))) return rows def summarize(name, rows, ms): q = [r for r in rows if r["has_pos"]] ql = [r for r in rows if r["has_near"]] if not q: print(f" {name:22s} khong co anh hoi nao co anh dung -- khong cham duoc") return None r1 = np.mean([r["ok1"] for r in q]) r5 = np.mean([r["ok5"] for r in q]) r10 = np.mean([r["ok10"] for r in q]) l1 = np.mean([r["loc1"] for r in ql]) if ql else float("nan") l5 = np.mean([r["loc5"] for r in ql]) if ql else float("nan") # Recall khi 0 nham: xep MOI anh hoi theo do giong top-1, dem so dung truoc # lan sai dau tien. Cho chua quay lai thi top-1 chac chan sai -- phai tinh. srt = sorted(rows, key=lambda r: -r["sim"]) k = 0 for r in srt: if not r["ok1"]: break k += 1 r0 = k / len(q) sim_ok = [r["sim"] for r in q if r["ok1"]] sim_bad = [r["sim"] for r in rows if not r["ok1"]] med = lambda v: float(np.median(v)) if v else float("nan") print(f" {name:22s} R@1 {r1:5.1%} R@5 {r5:5.1%} R@10 {r10:5.1%} | vi tri R@1 {l1:5.1%} " f"R@5 {l5:5.1%} | 0 nham {r0:5.1%} | giong: dung {med(sim_ok):.3f} sai {med(sim_bad):.3f}" f" | {ms:5.1f} ms/anh") return dict(name=name, r1=r1, r5=r5, r10=r10, l1=l1, l5=l5, r0=r0) def save_examples(path, nodes, rows, name, n_each=4): import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt ok = [r for r in rows if r["has_pos"] and r["ok1"]][:n_each] bad = sorted([r for r in rows if not r["ok1"]], key=lambda r: -r["sim"])[:n_each] pairs = [(r, "ĐÚNG") for r in ok] + [(r, "SAI") for r in bad] if not pairs: return fig, axes = plt.subplots(len(pairs), 2, figsize=(8, 2.9 * len(pairs))) axes = np.atleast_2d(axes) for k, (r, tag) in enumerate(pairs): a, b = nodes[r["i"]], nodes[r["top1"]] axes[k, 0].imshow(clahe(a["img"]), cmap="gray") axes[k, 0].set_title(f"hỏi: node {a['id']}", fontsize=9) axes[k, 1].imshow(clahe(b["img"]), cmap="gray") axes[k, 1].set_title(f"top-1 {tag}: node {b['id']}, cách {r['d1']:.1f} m / " f"{r['dyaw1']:.0f}°, giống {r['sim']:.2f}", fontsize=9, color="green" if tag == "ĐÚNG" else "red") for ax in axes[k]: ax.axis("off") fig.suptitle(f"VPR trên ảnh IR D410 — {name} (ảnh đã tăng tương phản để xem)", fontsize=11) fig.tight_layout() os.makedirs(os.path.dirname(path), exist_ok=True) fig.savefig(path, dpi=110) plt.close(fig) # ---------------------------------------------------------------- main def main(): ap = argparse.ArgumentParser() ap.add_argument("--db", required=True) ap.add_argument("--methods", default="tiny,cosplace,eigenplaces,dinov2") ap.add_argument("--excl-sec", type=float, default=30.0) ap.add_argument("--pos-m", type=float, default=2.0) ap.add_argument("--pos-deg", type=float, default=45.0) ap.add_argument("--device", default="cuda") ap.add_argument("--csv", default="logs/vpr_eval.csv") ap.add_argument("--fig", default="report/vpr/vi_du.png") a = ap.parse_args() nodes = load_db(a.db) if len(nodes) < 20: print(f"chi co {len(nodes)} anh dung duoc trong {a.db} (anh den bi bo) -- dung.") return 1 bright = np.mean([n["img"].mean() for n in nodes]) print(f"{a.db}: {len(nodes)} anh IR, do sang TB {bright:.1f}/255, " f"{(nodes[-1]['t'] - nodes[0]['t']) / 60:.1f} phut") names = a.methods.split(",") variants = {} if "tiny" in names: variants["tiny"] = ("tiny", None) models = load_models([m for m in names if m != "tiny"], a.device) raw = [n["img"] for n in nodes] enh = [clahe(im) for im in raw] nodot = [dedot(im) for im in raw] results, all_rows = [], {} print(f"\n===== loai tru +-{a.excl_sec:.0f} s | dung = < {a.pos_m} m & < {a.pos_deg:.0f} do =====") for tag, imgs in (("", raw), ("+clahe", enh), ("+khu_cham", nodot)): if "tiny" in variants: D, ms = desc_tiny(imgs) rows = evaluate(D, nodes, a.excl_sec, a.pos_m, a.pos_deg) nm = "tiny" + tag s = summarize(nm, rows, ms) if s: results.append(s) all_rows[nm] = rows for mname, (fn, wh) in models.items(): D, ms = torch_desc(fn, imgs, wh, a.device) rows = evaluate(D, nodes, a.excl_sec, a.pos_m, a.pos_deg) nm = mname + tag s = summarize(nm, rows, ms) if s: results.append(s) all_rows[nm] = rows if not results: return 1 q = sum(1 for r in next(iter(all_rows.values())) if r["has_pos"]) print(f"\n {q}/{len(nodes)} anh hoi co anh dung (cho robot quay lai cung huong)") best = max(results, key=lambda s: (s["r5"], s["r1"])) print(f" tot nhat theo R@5: {best['name']}") os.makedirs(os.path.dirname(a.csv) or ".", exist_ok=True) with open(a.csv, "w") as f: f.write("method,query_id,has_pos,top1_id,sim,dist_m,dyaw_deg,ok1,ok5,ok10\n") for nm, rows in all_rows.items(): for r in rows: f.write(f"{nm},{nodes[r['i']]['id']},{int(r['has_pos'])},{nodes[r['top1']]['id']}," f"{r['sim']:.4f},{r['d1']:.3f},{r['dyaw1']:.1f},{int(r['ok1'])}," f"{int(r['ok5'])},{int(r['ok10'])}\n") save_examples(a.fig, nodes, all_rows[best["name"]], best["name"]) print(f" csv -> {a.csv}\n anh vi du -> {a.fig}") return 0 if __name__ == "__main__": raise SystemExit(main())