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:
189
tools/reloc_pnp_eval.py
Normal file
189
tools/reloc_pnp_eval.py
Normal 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())
|
||||
Reference in New Issue
Block a user