diggop's picture
localization/: relocalization benchmark (part 2)
77d8cd6 verified
Raw History Blame Contribute Delete
4.41 kB
"""Evaluate camera relocalization on the mall localization benchmark (shipped as eval.py in the package; numpy + pandas only).
python eval.py --root <benchmark dir> --estimates <dir> your poses
python eval.py --root <benchmark dir> --baseline the shipped hloc baseline (reproduces benchmark.md)
<dir>/<walk>/<section>/poses_<map>to<query>.txt, one line per query image: `name qw qx qy qz tx ty tz`, world->camera
(COLMAP / hloc convention) in the frame of <walk>/<section>/reference/, whose unit is the metre. A query missing from the file
counts as a failure. Scored: the directions sections.parquet marks scored, and inside them the frames whose two references
agree (frames.parquet pgt_ok). Recall at (0.1 m, 1 deg), (0.25 m, 2 deg), (0.5 m, 5 deg), (1 m, 5 deg), (5 m, 10 deg).
"""
import argparse
import pathlib
import numpy as np
import pandas as pd
THRESHOLDS = [(0.1, 1.0), (0.25, 2.0), (0.5, 5.0), (1.0, 5.0), (5.0, 10.0)]
def qvec2rot(q):
w, x, y, z = q
return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
[2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
[2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]])
def read_poses(path: pathlib.Path) -> dict:
"""name -> (R world->cam, camera centre)."""
out = {}
if not path.exists():
return out
for line in path.read_text().splitlines():
p = line.split()
if len(p) != 8 or line.startswith("#"):
continue
R = qvec2rot(np.array(p[1:5], float)); t = np.array(p[5:8], float)
out[p[0]] = (R, -R.T @ t)
return out
def read_reference(images_txt: pathlib.Path) -> dict:
"""COLMAP images.txt -> name -> (R, centre); every other line is the 2D points."""
out, lines = {}, [l for l in images_txt.read_text().splitlines() if not l.startswith("#")]
for l in lines[::2]:
p = l.split()
if len(p) >= 10:
R = qvec2rot(np.array(p[1:5], float)); t = np.array(p[5:8], float)
out[p[9]] = (R, -R.T @ t)
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--root", required=True, type=pathlib.Path)
g = ap.add_mutually_exclusive_group(required=True)
g.add_argument("--estimates", type=pathlib.Path)
g.add_argument("--baseline", action="store_true")
ap.add_argument("--all", action="store_true", help="every query of every localized direction, not only the scored ones")
a = ap.parse_args()
S = pd.read_parquet(a.root / "sections.parquet")
S = S[S.direction.notna()] if a.all else S[S.scored]
rows = []
for _, s in S.iterrows():
d = a.root / s.walk / s.section
m, q = s.direction.split("->")
est_file = (d / "baseline" if a.baseline else a.estimates / s.walk / s.section) / f"poses_{m}to{q}.txt"
est, gt = read_poses(est_file), read_reference(d / "reference" / "images.txt")
F = pd.read_parquet(d / "frames.parquet")
F = F[(F.visit == int(q)) & F.registered & (True if a.all else F.pgt_ok)]
for n in F.name:
Rg, cg = gt[n]
if n in est:
Re, ce = est[n]
dt = float(np.linalg.norm(ce - cg)); dr = float(np.degrees(np.arccos(np.clip((np.trace(Re @ Rg.T) - 1) / 2, -1, 1))))
else:
dt = dr = np.inf
rows.append({"walk": s.walk, "section": s.section, "direction": s.direction, "query": n, "t_err_m": dt, "r_err_deg": dr})
E = pd.DataFrame(rows)
if E.empty:
raise SystemExit("nothing to evaluate")
rec = lambda X: {f"{T} m, {R:g} deg": float(((X.t_err_m <= T) & (X.r_err_deg <= R)).mean()) for T, R in THRESHOLDS}
print(f"{len(E)} queries over {E.groupby(['walk', 'section', 'direction']).ngroups} directions "
f"({'all' if a.all else 'scored'}; {'baseline' if a.baseline else a.estimates})")
for k, v in rec(E).items():
print(f" {k:>14}: {v:6.1%}")
fin = E[np.isfinite(E.t_err_m)]
print(f" median error of localized queries: {fin.t_err_m.median() * 100:.1f} cm, {fin.r_err_deg.median():.2f} deg")
per = E.groupby(["walk", "section", "direction"]).apply(lambda X: pd.Series({"queries": len(X), **rec(X)}), include_groups=False)
print(per.to_string(float_format=lambda x: f"{x:.2f}"))
if __name__ == "__main__":
main()