reloc eval: camera (VPR+PnP) ket hop LiDAR -- 25/09: 85->159, 28/09: 29->40, 0 chot sai ca hai ban

This commit is contained in:
trung09122002
2026-09-30 14:27:02 +07:00
parent 29d07e4db5
commit cccc048eaf
2 changed files with 251 additions and 0 deletions

View File

@@ -55,6 +55,9 @@ def main():
ap.add_argument("--db", required=True, help="DB ban do -- lay huong cac node ung vien VPR")
ap.add_argument("--vpr-yaw-deg", type=float, default=45.0,
help="huong chot phai lech huong node anh VPR it hon ngan nay")
ap.add_argument("--min-truth-overlap", type=float, default=0.0,
help="bo node hoi co truth_wall_overlap < nguong (dap an kem tin, can CSV "
"cua reloc_pnp_eval.py)")
a = ap.parse_args()
npose = node_poses(a.db)
yaw = {k: v[2] for k, v in npose.items()}
@@ -69,6 +72,7 @@ def main():
glob_ok=r["glob_ok"] == "1", verdict=r["glob_verdict"], ratio=float(r["glob_ratio"]),
g=(float(r["glob_x"]), float(r["glob_y"]), float(r["glob_th"])),
t=(float(r["truth_x"]), float(r["truth_y"]), float(r["truth_th"])))
q[qid]["tw"] = float(r.get("truth_wall_overlap", 1.0) or 1.0)
if int(r["rank"]) > 0:
cands[qid].append(dict(
rank=int(r["rank"]), node=int(r["vpr_node"]), sim=float(r["vpr_sim"]),
@@ -84,8 +88,21 @@ def main():
inl0=float(r.get("g3_inl0", 0) or 0),
dz=float(r.get("g3_dz", 0) or 0), tilt=float(r.get("g3_tilt", 0) or 0),
n=int(float(r.get("g3_nsrc", 0) or 0)))))
cands[qid][-1]["pnp"] = dict(
inl=int(float(r.get("pnp_inl", 0) or 0)),
p=(float(r.get("pnp_x", 0) or 0), float(r.get("pnp_y", 0) or 0),
float(r.get("pnp_th", 0) or 0)),
dz=float(r.get("pnp_dz", 0) or 0), tilt=float(r.get("pnp_tilt", 0) or 0))
q[qid]["s1"] = float(r["glob_s1"])
if a.min_truth_overlap > 0:
drop = [k for k, v in q.items() if v["tw"] < a.min_truth_overlap]
for k in drop:
del q[k]
cands.pop(k, None)
print(f"bo {len(drop)} node hoi co dap an kem tin (tuong trung < "
f"{a.min_truth_overlap:.0%}); con {len(q)}")
def correct(p, t):
return math.hypot(p[0] - t[0], p[1] - t[1]) < a.ok_m and ang(p[2], t[2]) < a.ok_deg
@@ -201,6 +218,51 @@ def main():
f"{uok:21d} {ubad:4d} {100.0 * uok / max(1, n):8.1f}%"
+ (" ⚠️" if ubad > 0 else ""))
# --- KET HOP camera (VPR + PnP) voi LiDAR: chot khi HAI nguon cung chi mot pose ---
# Camera: VPR goi y cho, PnP (diem dac trung + depth anh ban do) cho pose. LiDAR: khop cuc
# bo quanh node anh VPR (tu do huong = loc, gioi han huong = vloc). Chot pose LiDAR khi pose
# PnP trung mot trong hai (< 0.5 m, < 10 do); ung vien duoc chot MAU THUAN nhau -> khong
# chot. Robot chay tren san: nghiem PnP cao/nghieng bat thuong (suy bien) bi loai.
if any(c["pnp"]["inl"] > 0 for cs in cands.values() for c in cs):
def near(p, r, m=0.5, d=10.0):
return math.hypot(p[0] - r[0], p[1] - r[1]) < m and ang(p[2], r[2]) < d
def pq(v, p):
return v[min(len(v) - 1, int(p * len(v)))] if v else float("nan")
pg = sorted(c["pnp"]["inl"] for k, cs in cands.items() for c in cs
if c["pnp"]["inl"] > 0 and correct(c["pnp"]["p"], q[k]["t"]))
pb = sorted(c["pnp"]["inl"] for k, cs in cands.items() for c in cs
if c["pnp"]["inl"] > 0 and not correct(c["pnp"]["p"], q[k]["t"]))
print(f"\nPnP: so inlier khi pose PnP DUNG n={len(pg)} p10 {pq(pg, .1)} p50 {pq(pg, .5)} "
f"p90 {pq(pg, .9)} | khi SAI n={len(pb)} p10 {pq(pb, .1)} p50 {pq(pb, .5)} p90 {pq(pb, .9)}")
print(f"\n {'luat camera+LiDAR':30s} {'chot':>5s} {'DUNG':>5s} {'SAI':>4s} | "
f"{'HOP cong LiDAR: DUNG':>21s} {'SAI':>4s} {'dung/tong':>9s}")
for K in (1, 3, 5):
for nmin in (8, 12, 15, 20):
picks = {}
for k in q:
acc = []
for c in cands[k]:
pp = c["pnp"]
if (c["rank"] > K or pp["inl"] < nmin or abs(pp["dz"]) > 0.3
or pp["tilt"] > 10.0):
continue
if c["vscore"] > 0 and near(pp["p"], c["v"]):
acc.append(c["v"])
elif c["score"] > 0 and near(pp["p"], c["l"]):
acc.append(c["l"])
if acc and all(near(p, acc[0]) for p in acc[1:]):
picks[k] = acc[0]
ok = sum(1 for k, p in picks.items() if correct(p, q[k]["t"]))
u = dict(picks)
u.update(lidar)
uok = sum(1 for k, p in u.items() if correct(p, q[k]["t"]))
tag = " <- luat chot truoc" if (K, nmin) == (5, 12) else ""
print(f" top-{K} PnP>={nmin:2d} inlier + trung LiDAR {len(picks):5d} {ok:5d} "
f"{len(picks) - ok:4d} | {uok:21d} {len(u) - uok:4d} "
f"{100.0 * uok / max(1, n):8.1f}%" + (" ⚠️" if len(u) - uok > 0 else "") + tag)
# --- GICP 3D: bang chung doc lap ve hinh hoc cho gia thuyet cua VPR dan ---
rows3 = [(k, c) for k, cs in cands.items() for c in cs
if c["vscore"] > 0 and c["g3"]["n"] >= 200]

189
tools/reloc_pnp_eval.py Normal file
View File

@@ -0,0 +1,189 @@
#!/usr/bin/env python3
"""Xac minh ung vien VPR bang ANH: so khop diem dac trung (ORB) + PnP voi depth cua anh ban do.
Doc CSV cua `vslam_reloc_bench --fusion-csv` (moi dong: node hoi, ung vien VPR, pose LiDAR
toan cuc / cuc bo) va DB (sqlite, CHI DOC). Them cho moi dong:
pnp_nmatch, pnp_inl so cap diem khop qua ratio test / so inlier PnP RANSAC
pnp_x, pnp_y, pnp_th pose base cua node hoi trong map theo PnP
pnp_dz, pnp_tilt do cao (m) / nghieng (do) cua base theo PnP -- robot chay tren san
nen phai ~0; lech nhieu = nghiem PnP suy bien
truth_wall_overlap ty le diem tuong LiDAR cua node hoi (theo pose TOI UU) nam trong
10 cm tuong cua phan ban do -- thap = dap an khong dang tin vi ban
do lech (2026-09-30: ban 28/09 lech sau mot quang dung 285 s)
============ VI SAO PnP, KHONG CHI VPR + HINH KHOI DEPTH ============
Do 2026-09-30 tren ban 28/09: VPR + trung khop hinh khoi depth chot SAI 28 lan, gan het la
lat NGUOC 170-180 do trong hanh lang -- nhin xuoi hay nguoc cung hinh dang, nen camera sai
CUNG cho voi LiDAR. Diem dac trung nho (goc cua, poster, van go) nhin nguoc thi KHAC HAN: thu
nhanh 29 ca lat do -> 18 ca PnP khong ra nghiem, 11 ca chi 5-13 inlier.
python3 tools/reloc_pnp_eval.py --db DB --split-id N --fusion-csv IN.csv --out OUT.csv
"""
import argparse
import csv
import math
import os
import sqlite3
import sys
import cv2
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import render_map as rm # noqa: E402 -- dung chung giai ma RVL / calib / ma tran nen
NEW_COLS = ["pnp_nmatch", "pnp_inl", "pnp_x", "pnp_y", "pnp_th", "pnp_dz", "pnp_tilt",
"truth_wall_overlap"]
def to4(t34):
t = np.eye(4)
t[:3, :] = t34
return t
class Db:
"""Anh, depth, calib, pose toi uu, tuong LiDAR cua tung node. Cache theo id."""
def __init__(self, path):
self.c = sqlite3.connect(f"file:{path}?mode=ro", uri=True).cursor()
ids_b, poses_b = self.c.execute("select opt_ids, opt_poses from Admin").fetchone()
ids = np.frombuffer(rm.mat(ids_b), dtype=np.int32)
P = np.frombuffer(rm.mat(poses_b), dtype=np.float32).reshape(-1, 3, 4).astype(np.float64)
self.pose = {int(i): to4(P[k]) for k, i in enumerate(ids)}
self.clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8)) # anh IR toi: x2.7 diem
self.orb = cv2.ORB_create(nfeatures=1500, fastThreshold=7)
self.feat, self.depth = {}, {}
def features(self, i):
"""(keypoints, descriptors, K, T_base<-optical, (w, h)) cua anh IR trai."""
if i not in self.feat:
row = self.c.execute("select image, calibration from Data where id=?", (i,)).fetchone()
if row is None or row[0] is None or row[1] is None:
self.feat[i] = ([], None, None, None, (0, 0))
else:
img = cv2.imdecode(np.frombuffer(row[0], np.uint8), cv2.IMREAD_GRAYSCALE)
hdr, K, Tc = rm.decode_calib(row[1])
kp, des = self.orb.detectAndCompute(self.clahe.apply(img), None)
self.feat[i] = (kp, des, K, to4(Tc), (hdr[4], hdr[5]))
return self.feat[i]
def depth_m(self, i):
if i not in self.depth:
row = self.c.execute("select depth from Data where id=?", (i,)).fetchone()
w, h = self.features(i)[4]
if row is None or row[0] is None or w == 0:
self.depth[i] = np.zeros((1, 1))
else:
self.depth[i] = rm.decode_depth(row[0]).reshape(h, w).astype(np.float64) * 0.001
return self.depth[i]
def wall_cells(self, i):
"""Diem tuong LiDAR (luoi cuc bo trong DB) cua node, frame map, theo pose toi uu."""
row = self.c.execute("select obstacle_cells from Data where id=?", (i,)).fetchone()
if row is None or row[0] is None or i not in self.pose:
return np.zeros((0, 2))
q = np.frombuffer(rm.mat(row[0]), dtype=np.float32).reshape(-1, 2).astype(np.float64)
T = self.pose[i]
return q @ T[:2, :2].T + T[:2, 3]
def pnp(self, qid, mid, bf):
"""Pose base cua node hoi `qid` trong map, tu diem khop voi anh + depth node ban do `mid`."""
kq, dq, Kq, Tq, _ = self.features(qid)
km, dm, Km, Tm, _ = self.features(mid)
if dq is None or dm is None or len(kq) < 8 or len(km) < 8:
return 0, 0, None
good = [m[0] for m in bf.knnMatch(dq, dm, k=2)
if len(m) == 2 and m[0].distance < 0.8 * m[1].distance]
dep = self.depth_m(mid)
Twm = self.pose[mid] @ Tm # map <- optical cua node ban do
obj, img = [], []
for g in good:
u, v = km[g.trainIdx].pt
r, cc = int(round(v)), int(round(u))
if not (0 <= r < dep.shape[0] and 0 <= cc < dep.shape[1]):
continue
z = dep[r, cc]
if not 0.3 < z < 5.0:
continue
pc = np.array([(u - Km[0, 2]) * z / Km[0, 0], (v - Km[1, 2]) * z / Km[1, 1], z, 1.0])
obj.append((Twm @ pc)[:3])
img.append(kq[g.queryIdx].pt)
if len(obj) < 8:
return len(good), 0, None
ok, rvec, tvec, inl = cv2.solvePnPRansac(
np.array(obj), np.array(img), Kq, None, iterationsCount=300, reprojectionError=4.0,
confidence=0.999, flags=cv2.SOLVEPNP_EPNP)
if not ok or inl is None:
return len(good), 0, None
R, _ = cv2.Rodrigues(rvec)
Tcw = np.eye(4)
Tcw[:3, :3] = R
Tcw[:3, 3] = tvec.ravel() # optical <- map
Twb = np.linalg.inv(Tcw) @ np.linalg.inv(Tq) # map <- base cua node hoi
tilt = math.degrees(math.acos(max(-1.0, min(1.0, Twb[2, 2]))))
return len(good), len(inl), (Twb[0, 3], Twb[1, 3], math.atan2(Twb[1, 0], Twb[0, 0]),
Twb[2, 3], tilt)
def wall_overlap_fn(db, split):
"""f(id) = ty le diem tuong cua node nam trong 10 cm tuong cua cac node id < split."""
cells = set()
for i in db.pose:
if i < split:
for x, y in np.floor(db.wall_cells(i) / 0.05).astype(np.int64):
cells.add((int(x), int(y)))
near = [(dx, dy) for dx in range(-2, 3) for dy in range(-2, 3)]
def f(i):
w = db.wall_cells(i)
if len(w) < 30:
return 0.0
k = np.floor(w / 0.05).astype(np.int64)
return sum(1 for x, y in k if any((x + dx, y + dy) in cells for dx, dy in near)) / len(k)
return f
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--db", required=True, help="DB ban do (cung DB voi bench --split-id)")
ap.add_argument("--split-id", type=int, required=True)
ap.add_argument("--fusion-csv", required=True)
ap.add_argument("--out", required=True)
a = ap.parse_args()
db = Db(a.db)
bf = cv2.BFMatcher(cv2.NORM_HAMMING)
overlap = wall_overlap_fn(db, a.split_id)
rows = list(csv.DictReader(open(a.fusion_csv)))
if not rows:
print("CSV rong")
return 1
tw, n_pnp, n_ok = {}, 0, 0
with open(a.out, "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0].keys()) + NEW_COLS)
w.writeheader()
for k, r in enumerate(rows):
qid, mid = int(r["query_id"]), int(r["vpr_node"])
if qid not in tw:
tw[qid] = overlap(qid)
out = dict(r, truth_wall_overlap=f"{tw[qid]:.3f}", pnp_nmatch=0, pnp_inl=0, pnp_x=0,
pnp_y=0, pnp_th=0, pnp_dz=0, pnp_tilt=0)
if int(r["rank"]) > 0 and mid in db.pose:
nm, ni, est = db.pnp(qid, mid, bf)
n_pnp += 1
out.update(pnp_nmatch=nm, pnp_inl=ni)
if est is not None:
n_ok += 1
out.update(pnp_x=f"{est[0]:.3f}", pnp_y=f"{est[1]:.3f}", pnp_th=f"{est[2]:.4f}",
pnp_dz=f"{est[3]:.3f}", pnp_tilt=f"{est[4]:.2f}")
w.writerow(out)
if (k + 1) % 200 == 0:
print(f" {k + 1}/{len(rows)} dong", flush=True)
bad_truth = sum(1 for v in tw.values() if v < 0.8)
print(f"{len(tw)} node hoi, {n_pnp} cap (hoi, ung vien), PnP ra nghiem {n_ok}; "
f"dap an kem tin (tuong trung < 80%): {bad_truth} -> {a.out}")
return 0
if __name__ == "__main__":
raise SystemExit(main())