Download Scripts/cad_fidelity.py from moiaraya/I-AsSET: direct link, hf CLI and curl.
- Browser
- Download file 59.8 kB
-
https://huggingface.co/datasets/moiaraya/I-AsSET/resolve/main/Scripts/cad_fidelity.py
- Command line
-
hf download hf://datasets/moiaraya/I-AsSET/Scripts/cad_fidelity.py
-
curl -L -o cad_fidelity.py https://huggingface.co/datasets/moiaraya/I-AsSET/resolve/main/Scripts/cad_fidelity.py
59.8 kB
| #!/usr/bin/env python3 | |
| """ | |
| CAD fidelity evaluation of reconstructed assets (3DGS / MeshyAI / TRELLIS ...). | |
| Pipeline | |
| export .blend -> .ply (via headless Blender, modifiers and transforms applied, units in mm) | |
| register reconstruction -> CAD, similarity transform (multi-start + ICP with scale) | |
| evaluate Chamfer, Hausdorff, HD95, F-score, scale error, OBB extent error; tables + plots | |
| view interactive 3D check of the alignment (Open3D GUI with buttons) and | |
| vector-PDF export of the current view for publication figures | |
| all export + register + evaluate | |
| Expected layout (as in the I-AsSET repository): | |
| <root>/Manual/*.blend CAD references | |
| <root>/<METHOD>/*.blend reconstructions (one folder per method) | |
| Classes are matched by file stem (case and punctuation insensitive). | |
| Requirements: numpy scipy trimesh>=4 open3d>=0.17 pandas matplotlib, and Blender (CLI) for `export`. | |
| Examples | |
| python cad_fidelity.py all --root Assets/CADs --out fidelity_out --blender /path/to/blender | |
| python cad_fidelity.py view --root Assets/CADs --out fidelity_out --methods TRELLIS | |
| # publication-style qualitative views: white background, mm axes, fixed colour bar (0 to 1.5 mm) | |
| python cad_fidelity.py view --root Assets/CADs --out fidelity_out --background white \ | |
| --mm-axes --colorbar --dev-max-mm 1.5 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import itertools | |
| import json | |
| import re | |
| import subprocess | |
| import sys | |
| import tempfile | |
| from concurrent.futures import ThreadPoolExecutor | |
| from pathlib import Path | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import open3d as o3d | |
| import pandas as pd | |
| import trimesh | |
| from matplotlib import cm | |
| from matplotlib.collections import LineCollection, PolyCollection | |
| from matplotlib.colors import Normalize | |
| from scipy.spatial import cKDTree | |
| from scipy.spatial.transform import Rotation | |
| # Embed text as TrueType (editable in Illustrator / Inkscape) instead of Type 3 when saving PDF | |
| matplotlib.rcParams["pdf.fonttype"] = 42 | |
| matplotlib.rcParams["ps.fonttype"] = 42 | |
| # ---------------------------------------------------------------------------------------------- | |
| # Blender side (runs inside Blender, writes vertices/faces in millimetres to an .npz) | |
| # ---------------------------------------------------------------------------------------------- | |
| BLENDER_SCRIPT = r''' | |
| import re, sys | |
| import bpy | |
| import numpy as np | |
| out, mm_per_bu, exclude = sys.argv[sys.argv.index("--") + 1:][:3] | |
| mm_per_bu = float(mm_per_bu) | |
| scene = bpy.context.scene | |
| if mm_per_bu <= 0: # auto: Blender unit scale (metres per BU) converted to mm | |
| mm_per_bu = scene.unit_settings.scale_length * 1000.0 | |
| dg = bpy.context.evaluated_depsgraph_get() | |
| V, F, names, off = [], [], [], 0 | |
| for ob in scene.objects: | |
| if ob.type not in {"MESH", "CURVE", "SURFACE", "META", "FONT"}: | |
| continue | |
| if ob.hide_get() or ob.hide_viewport: | |
| continue | |
| if exclude and re.search(exclude, ob.name): | |
| continue | |
| ev = ob.evaluated_get(dg) | |
| me = ev.to_mesh() | |
| me.calc_loop_triangles() | |
| n, m = len(me.vertices), len(me.loop_triangles) | |
| if n == 0 or m == 0: | |
| ev.to_mesh_clear() | |
| continue | |
| co = np.empty(n * 3, np.float32) | |
| me.vertices.foreach_get("co", co) | |
| tri = np.empty(m * 3, np.int32) | |
| me.loop_triangles.foreach_get("vertices", tri) | |
| co = co.reshape(-1, 3).astype(np.float64) | |
| tri = tri.reshape(-1, 3).astype(np.int64) | |
| mw = np.array(ob.matrix_world, dtype=np.float64) | |
| co = co @ mw[:3, :3].T + mw[:3, 3] | |
| if np.linalg.det(mw[:3, :3]) < 0: | |
| tri = tri[:, ::-1] | |
| V.append(co * mm_per_bu) | |
| F.append(tri + off) | |
| off += n | |
| names.append(ob.name) | |
| ev.to_mesh_clear() | |
| if not V: | |
| raise SystemExit("no mesh objects exported") | |
| np.savez(out, V=np.concatenate(V), F=np.concatenate(F), names=np.array(names), mm_per_bu=mm_per_bu) | |
| ''' | |
| # ---------------------------------------------------------------------------------------------- | |
| # Helpers | |
| # ---------------------------------------------------------------------------------------------- | |
| COLS = [ # key, header, decimals | |
| ("chamfer_pct", "CD-L1 [% diag]", 3), | |
| ("chamfer_mm", "CD-L1 [mm]", 3), | |
| ("hd95_pct", "HD95 [% diag]", 3), | |
| ("hd_pct", "HD [% diag]", 3), | |
| ("f1", "F@1% [-]", 3), | |
| ("f2", "F@2% [-]", 3), | |
| ("scale_err_abs", "|scale err| [%]", 2), | |
| ("bbox_err_pct", "OBB err [%]", 2), | |
| ] | |
| PLOT_METRICS = [ | |
| ("chamfer_pct", "Chamfer-L1 [% of diagonal]", "lower is better"), | |
| ("hd95_pct", "HD95 [% of diagonal]", "lower is better"), | |
| ("hd_pct", "Hausdorff [% of diagonal]", "lower is better"), | |
| ("f1", "F-score @ 1% of diagonal", "higher is better"), | |
| ("scale_err_abs", "|Scale error| [%]", "lower is better"), | |
| ("bbox_err_pct", "OBB extent error [%]", "lower is better"), | |
| ] | |
| def norm(s: str) -> str: | |
| return re.sub(r"[^a-z0-9]", "", s.lower()) | |
| def pastel_viridis(n: int, lo=0.1, hi=0.9, mix=0.45): | |
| c = cm.viridis(np.linspace(lo, hi, n))[:, :3] | |
| return (1 - mix) * c + mix | |
| def sample(mesh: trimesh.Trimesh, n: int, seed: int) -> np.ndarray: | |
| pts, _ = trimesh.sample.sample_surface(mesh, n, seed=seed) | |
| return np.asarray(pts, dtype=np.float64) | |
| def obb_diag(mesh: trimesh.Trimesh) -> float: | |
| return float(np.linalg.norm(mesh.bounding_box_oriented.extents)) | |
| def to_pcd(p: np.ndarray) -> o3d.geometry.PointCloud: | |
| pc = o3d.geometry.PointCloud() | |
| pc.points = o3d.utility.Vector3dVector(p) | |
| return pc | |
| def apply_T(p: np.ndarray, T: np.ndarray) -> np.ndarray: | |
| return p @ T[:3, :3].T + T[:3, 3] | |
| def scale_of(T: np.ndarray) -> float: | |
| return float(np.cbrt(np.linalg.det(T[:3, :3]))) | |
| def reg_path(out: Path, method: str, key: str) -> Path: | |
| return out / "registrations" / method / f"{key}.json" | |
| def load_flags(out: Path) -> set: | |
| f = out / "flags.json" | |
| return set(json.loads(f.read_text())) if f.exists() else set() | |
| def save_flags(out: Path, flags: set): | |
| (out / "flags.json").write_text(json.dumps(sorted(flags), indent=1)) | |
| def index_meshes(out: Path) -> dict: | |
| idx = {} | |
| root = out / "meshes" | |
| if root.exists(): | |
| for d in sorted(root.iterdir()): | |
| if d.is_dir(): | |
| idx[d.name] = {norm(p.stem): p for p in sorted(d.glob("*.ply"))} | |
| return idx | |
| def get_pairs(args): | |
| """List of (method, key, cad_ply, rec_ply).""" | |
| idx = index_meshes(args.out) | |
| cad = idx.get(args.cad_folder) | |
| if not cad: | |
| sys.exit(f"No exported CAD meshes in {args.out / 'meshes' / args.cad_folder}. Run `export` first.") | |
| wanted = {norm(c) for c in args.classes} if args.classes else None | |
| pairs = [] | |
| for m, files in idx.items(): | |
| if m == args.cad_folder or (args.methods and m not in args.methods): | |
| continue | |
| extra = [] | |
| for k, p in files.items(): | |
| if wanted and k not in wanted: | |
| continue | |
| if k in cad: | |
| pairs.append((m, k, cad[k], p)) | |
| else: | |
| extra.append(p.stem) | |
| missing = [cad[k].stem for k in cad if k not in files and (not wanted or k in wanted)] | |
| if extra: | |
| print(f"[warn] {m}: {len(extra)} files without matching CAD name (e.g. {extra[:3]})") | |
| if missing: | |
| print(f"[warn] {m}: {len(missing)} CADs without reconstruction (e.g. {missing[:3]})") | |
| return pairs | |
| # ---------------------------------------------------------------------------------------------- | |
| # 1) Export | |
| # ---------------------------------------------------------------------------------------------- | |
| SRC_EXT = (".blend", ".glb", ".gltf", ".obj", ".ply", ".stl") | |
| def export_generic(src: Path, ply: Path, unit_to_mm: float) -> str: | |
| """Non-Blender sources (glb, obj, ...): flatten the scene graph, drop textures, scale to mm.""" | |
| scene = trimesh.load(src, force="scene") | |
| geoms = [g for g in scene.dump() if isinstance(g, trimesh.Trimesh)] | |
| if not geoms: | |
| raise RuntimeError(f"No triangle meshes in {src}") | |
| V, F, off = [], [], 0 | |
| for g in geoms: | |
| V.append(np.asarray(g.vertices)) | |
| F.append(np.asarray(g.faces) + off) | |
| off += len(g.vertices) | |
| mesh = trimesh.Trimesh(np.concatenate(V) * unit_to_mm, np.concatenate(F), process=False) | |
| mesh.export(ply) | |
| return (f"export {ply.parent.name}/{ply.name}: geometries={len(geoms)}, unit->mm x{unit_to_mm:g}, " | |
| f"V={len(mesh.vertices)}, F={len(mesh.faces)}, OBB diag={obb_diag(mesh):.1f} mm") | |
| def export_one(blend: Path, ply: Path, blender: str, mm_per_bu: float, exclude: str, force: bool, | |
| glb_unit_to_mm: float = 1000.0) -> str: | |
| if ply.exists() and not force: | |
| return f"skip {ply.parent.name}/{ply.name}" | |
| ply.parent.mkdir(parents=True, exist_ok=True) | |
| if blend.suffix.lower() != ".blend": | |
| return export_generic(blend, ply, glb_unit_to_mm) | |
| with tempfile.TemporaryDirectory() as td: | |
| script, npz = Path(td) / "exp.py", Path(td) / "m.npz" | |
| script.write_text(BLENDER_SCRIPT) | |
| cmd = [blender, "-b", str(blend), "--python-exit-code", "1", "--python", str(script), | |
| "--", str(npz), str(mm_per_bu), exclude] | |
| r = subprocess.run(cmd, capture_output=True, text=True) | |
| if r.returncode != 0 or not npz.exists(): | |
| raise RuntimeError(f"Blender failed on {blend}:\n{r.stdout[-800:]}\n{r.stderr[-800:]}") | |
| d = np.load(npz) | |
| mesh = trimesh.Trimesh(d["V"], d["F"], process=False) | |
| mesh.export(ply) | |
| return (f"export {ply.parent.name}/{ply.name}: objects={list(map(str, d['names']))}, " | |
| f"mm/BU={float(d['mm_per_bu']):g}, V={len(mesh.vertices)}, F={len(mesh.faces)}, " | |
| f"OBB diag={obb_diag(mesh):.1f} mm") | |
| def cmd_export(args): | |
| root = args.root | |
| folders = [d for d in sorted(root.iterdir()) if d.is_dir()] | |
| jobs = [] | |
| for d in folders: | |
| if args.methods and d.name != args.cad_folder and d.name not in args.methods: | |
| continue | |
| for b in sorted(p for p in d.rglob("*") if p.is_file() and p.suffix.lower() in SRC_EXT): | |
| jobs.append((b, args.out / "meshes" / d.name / f"{b.stem}.ply")) | |
| print(f"{len(jobs)} source files found ({', '.join(SRC_EXT)})") | |
| with ThreadPoolExecutor(args.jobs) as ex: | |
| futs = [ex.submit(export_one, b, p, args.blender, args.mm_per_bu, args.exclude_objects, args.force, | |
| args.glb_unit_to_mm) for b, p in jobs] | |
| for f in futs: | |
| print(f.result()) | |
| print("Check the 'OBB diag' values: if they look off by 1000x, set --mm-per-bu explicitly.") | |
| # ---------------------------------------------------------------------------------------------- | |
| # 2) Registration | |
| # ---------------------------------------------------------------------------------------------- | |
| def octa_rotations(): | |
| mats = [] | |
| for perm in itertools.permutations(range(3)): | |
| for signs in itertools.product([1, -1], repeat=3): | |
| M = np.zeros((3, 3)) | |
| for i, (j, s) in enumerate(zip(perm, signs)): | |
| M[i, j] = s | |
| if np.linalg.det(M) > 0: | |
| mats.append(M) | |
| return mats | |
| def pca_frame(p): | |
| w, v = np.linalg.eigh(np.cov((p - p.mean(0)).T)) | |
| v = v[:, ::-1].copy() | |
| if np.linalg.det(v) < 0: | |
| v[:, 2] *= -1 | |
| return v | |
| def pca_rotations(src, tgt): | |
| Vs, Vt = pca_frame(src), pca_frame(tgt) | |
| out = [] | |
| for s in itertools.product([1, -1], repeat=3): | |
| if np.prod(s) > 0: | |
| out.append(Vt @ np.diag(s) @ Vs.T) | |
| return out | |
| def make_init(R, c_src, c_tgt): | |
| T = np.eye(4) | |
| T[:3, :3] = R | |
| T[:3, 3] = c_tgt - R @ c_src | |
| return T | |
| def icp_multiscale(src, tgt, T, thresholds, iters, scaling): | |
| reg = o3d.pipelines.registration | |
| est = reg.TransformationEstimationPointToPoint(with_scaling=scaling) | |
| for thr, it in zip(thresholds, iters): | |
| crit = reg.ICPConvergenceCriteria(relative_fitness=1e-7, relative_rmse=1e-7, max_iteration=it) | |
| T = reg.registration_icp(src, tgt, thr, T, est, crit).transformation | |
| return np.asarray(T) | |
| def chamfer_np(a, b): | |
| return 0.5 * (cKDTree(b).query(a)[0].mean() + cKDTree(a).query(b)[0].mean()) | |
| def score(src, T, tgt): | |
| s = scale_of(T) | |
| if not (0.5 < s < 2.0): | |
| return np.inf | |
| return chamfer_np(apply_T(src, T), tgt) | |
| def fpfh_init(src, tgt, diag, seed): | |
| reg = o3d.pipelines.registration | |
| voxel = diag / 40.0 | |
| def prep(p): | |
| pc = to_pcd(p).voxel_down_sample(voxel) | |
| pc.estimate_normals(o3d.geometry.KDTreeSearchParamHybrid(radius=2 * voxel, max_nn=30)) | |
| f = reg.compute_fpfh_feature(pc, o3d.geometry.KDTreeSearchParamHybrid(radius=5 * voxel, max_nn=100)) | |
| return pc, f | |
| try: | |
| o3d.utility.random.seed(seed) | |
| (s, sf), (t, tf) = prep(src), prep(tgt) | |
| r = reg.registration_ransac_based_on_feature_matching( | |
| s, t, sf, tf, True, 1.5 * voxel, reg.TransformationEstimationPointToPoint(False), 3, | |
| [reg.CorrespondenceCheckerBasedOnEdgeLength(0.9), reg.CorrespondenceCheckerBasedOnDistance(1.5 * voxel)], | |
| reg.RANSACConvergenceCriteria(100000, 0.999)) | |
| return np.asarray(r.transformation) if len(r.correspondence_set) >= 3 else None | |
| except Exception: | |
| return None | |
| def register_pair(cad, rec, scaling=True, init_scale="manual", extra_inits=0, seed=0): | |
| """Return similarity transform T (4x4) mapping the exported reconstruction frame into the CAD frame.""" | |
| rng = np.random.default_rng(seed) | |
| diag = obb_diag(cad) | |
| ratio = obb_diag(rec) / diag | |
| auto_scaled = init_scale == "auto" or not (0.5 < ratio < 2.0) | |
| s0 = diag / obb_diag(rec) if auto_scaled else 1.0 | |
| S0 = np.diag([s0, s0, s0, 1.0]) | |
| cad_pts = sample(cad, 30000, seed) | |
| rec_pts = s0 * sample(rec, 30000, seed + 1) | |
| tgt_f, src_f = to_pcd(cad_pts), to_pcd(rec_pts) | |
| tgt_c, src_c = to_pcd(cad_pts[:4000]), to_pcd(rec_pts[:4000]) | |
| c_cad, c_rec = cad_pts.mean(0), rec_pts.mean(0) | |
| cands = [(f"octa{i}", make_init(R, c_rec, c_cad)) for i, R in enumerate(octa_rotations())] | |
| cands += [(f"pca{i}", make_init(R, c_rec, c_cad)) for i, R in enumerate(pca_rotations(rec_pts, cad_pts))] | |
| Tf = fpfh_init(rec_pts, cad_pts, diag, seed) | |
| if Tf is not None: | |
| cands.append(("fpfh", Tf)) | |
| if extra_inits: | |
| Rs = Rotation.random(extra_inits, random_state=rng).as_matrix().reshape(-1, 3, 3) | |
| cands += [(f"rand{i}", make_init(R, c_rec, c_cad)) for i, R in enumerate(Rs)] | |
| thr_c = [0.10 * diag, 0.05 * diag, 0.02 * diag] | |
| scored = [] | |
| for name, T0 in cands: | |
| T = icp_multiscale(src_c, tgt_c, T0, thr_c, [20, 20, 20], scaling) | |
| scored.append((score(rec_pts[:4000], T, cad_pts[:4000]), name, T)) | |
| scored.sort(key=lambda x: x[0]) | |
| thr_f = [0.02 * diag, 0.01 * diag, 0.005 * diag] | |
| best = None | |
| for _, name, T in scored[:3]: | |
| T2 = icp_multiscale(src_f, tgt_f, T, thr_f, [50, 50, 100], scaling) | |
| s = score(rec_pts, T2, cad_pts) | |
| if best is None or s < best[0]: | |
| best = (s, name, T2) | |
| s, name, T = best | |
| T_total = T @ S0 | |
| return dict(T=T_total, scale=scale_of(T_total), init=name, score_mm=float(s), diag_mm=diag, | |
| n_starts=len(cands), auto_scaled=bool(auto_scaled)) | |
| def cmd_register(args): | |
| flags = load_flags(args.out) | |
| todo = get_pairs(args) | |
| if args.retry_flagged: | |
| todo = [t for t in todo if f"{t[0]}/{t[1]}" in flags] | |
| extra = args.extra_inits if args.extra_inits is not None else (300 if args.retry_flagged else 0) | |
| for i, (m, k, cp, rp) in enumerate(todo, 1): | |
| dst = reg_path(args.out, m, k) | |
| if dst.exists() and args.skip_existing and not args.retry_flagged: | |
| continue | |
| if dst.exists() and not args.retry_flagged and not args.overwrite_manual: | |
| try: | |
| is_manual = bool(json.loads(dst.read_text()).get("manual", False)) | |
| except Exception: | |
| is_manual = False | |
| if is_manual: | |
| print(f"[{i}/{len(todo)}] {m}/{cp.stem}: manual registration kept (use --overwrite-manual)") | |
| continue | |
| cad, rec = trimesh.load(cp, process=False), trimesh.load(rp, process=False) | |
| mode = "auto" if m in (args.auto_scale_methods or []) else args.init_scale | |
| res = register_pair(cad, rec, scaling=not args.rigid, init_scale=mode, | |
| extra_inits=extra, seed=args.seed) | |
| dst.parent.mkdir(parents=True, exist_ok=True) | |
| dst.write_text(json.dumps(dict(method=m, cls=cp.stem, T=res["T"].tolist(), scale=res["scale"], | |
| init=res["init"], score_mm=res["score_mm"], diag_mm=res["diag_mm"], | |
| auto_scaled=res["auto_scaled"]), indent=1)) | |
| flags.discard(f"{m}/{k}") | |
| print(f"[{i}/{len(todo)}] {m}/{cp.stem}: scale={res['scale']:.4f} chamfer~{res['score_mm']:.3f} mm " | |
| f"init={res['init']} ({res['n_starts']} starts){' [auto-scaled]' if res['auto_scaled'] else ''}") | |
| save_flags(args.out, flags) | |
| # ---------------------------------------------------------------------------------------------- | |
| # 3) Metrics, tables, plots | |
| # ---------------------------------------------------------------------------------------------- | |
| def evaluate_pair(cad, rec, T, n, seed): | |
| V = apply_T(np.asarray(rec.vertices), T) | |
| rec_t = trimesh.Trimesh(V, rec.faces, process=False) | |
| a, b = sample(rec_t, n, seed), sample(cad, n, seed + 1) | |
| d_ab = cKDTree(b).query(a)[0] | |
| d_ba = cKDTree(a).query(b)[0] | |
| diag = obb_diag(cad) | |
| ext_c = np.sort(cad.bounding_box_oriented.extents)[::-1] | |
| ext_r = np.sort(rec_t.bounding_box_oriented.extents)[::-1] | |
| row = dict( | |
| chamfer_mm=0.5 * (d_ab.mean() + d_ba.mean()), | |
| chamfer_l2_mm2=(d_ab ** 2).mean() + (d_ba ** 2).mean(), | |
| hd_mm=max(d_ab.max(), d_ba.max()), | |
| hd95_mm=max(np.percentile(d_ab, 95), np.percentile(d_ba, 95)), | |
| diag_mm=diag, | |
| bbox_err_pct=float(np.mean(np.abs(ext_r - ext_c) / ext_c) * 100), | |
| ) | |
| for name, frac in (("f1", 0.01), ("f2", 0.02)): | |
| tau = frac * diag | |
| p, r = (d_ab < tau).mean(), (d_ba < tau).mean() | |
| row[name] = 2 * p * r / (p + r + 1e-12) | |
| for k in ("chamfer", "hd", "hd95"): | |
| row[f"{k}_pct"] = row[f"{k}_mm"] / diag * 100 | |
| return row | |
| def cell(series, nd): | |
| v = series.dropna() | |
| return "n/a" if v.empty else f"{v.mean():.{nd}f} ± {v.std():.{nd}f}" | |
| def fmt_table(df, methods): | |
| header = ["Method", "n"] + [c[1] for c in COLS] | |
| rows = [] | |
| for m in methods: | |
| g = df[df.method == m] | |
| rows.append([m, str(len(g))] + [cell(g[c], nd) for c, _, nd in COLS]) | |
| md = ["| " + " | ".join(header) + " |", "|" + "---|" * len(header)] | |
| md += ["| " + " | ".join(r) + " |" for r in rows] | |
| tex = ["\\begin{tabular}{l" + "r" * (len(header) - 1) + "}", "\\toprule", | |
| " & ".join(h.replace("%", "\\%").replace("_", "\\_") for h in header) + " \\\\", "\\midrule"] | |
| tex += [" & ".join(c.replace("±", "$\\pm$") for c in r) + " \\\\" for r in rows] | |
| tex += ["\\bottomrule", "\\end{tabular}"] | |
| return "\n".join(md), "\n".join(tex) | |
| def save_fig(fig, out: Path, name: str): | |
| fig.savefig(out / f"{name}.png", dpi=300, bbox_inches="tight") | |
| fig.savefig(out / f"{name}.pdf", bbox_inches="tight") | |
| plt.close(fig) | |
| def make_plots(df, out: Path, methods): | |
| colors = pastel_viridis(len(methods)) | |
| rng = np.random.default_rng(0) | |
| fig, axes = plt.subplots(2, 3, figsize=(12, 7)) | |
| for ax, (col, label, better) in zip(axes.ravel(), PLOT_METRICS): | |
| data = [df.loc[df.method == m, col].dropna().values for m in methods] | |
| bp = ax.boxplot(data, patch_artist=True, widths=0.55, showfliers=False, medianprops=dict(color="0.25")) | |
| for patch, c in zip(bp["boxes"], colors): | |
| patch.set_facecolor(c) | |
| patch.set_edgecolor("0.35") | |
| for i, (d, c) in enumerate(zip(data, colors), 1): | |
| ax.scatter(i + rng.uniform(-0.15, 0.15, len(d)), d, s=14, color=c, edgecolor="0.3", | |
| linewidth=0.4, zorder=3) | |
| ax.set_xticks(range(1, len(methods) + 1)) | |
| ax.set_xticklabels(methods) | |
| ax.set_title(f"{label}\n({better})", fontsize=9) | |
| ax.grid(axis="y", alpha=0.3) | |
| fig.tight_layout() | |
| save_fig(fig, out, "fig_metrics_boxplots") | |
| piv = df.pivot(index="cls", columns="method", values="chamfer_pct")[methods] | |
| piv = piv.loc[piv.mean(axis=1).sort_values().index] | |
| fig, ax = plt.subplots(figsize=(max(10, 0.45 * len(piv)), 4.5)) | |
| w = 0.8 / len(methods) | |
| x = np.arange(len(piv)) | |
| for i, (m, c) in enumerate(zip(methods, colors)): | |
| ax.bar(x + (i - (len(methods) - 1) / 2) * w, piv[m].values, w, label=m, color=c, edgecolor="0.35", linewidth=0.5) | |
| ax.set_xticks(x) | |
| ax.set_xticklabels(piv.index, rotation=70, ha="right", fontsize=8) | |
| ax.set_ylabel("Chamfer-L1 [% of CAD diagonal]") | |
| ax.legend(frameon=False) | |
| ax.grid(axis="y", alpha=0.3) | |
| fig.tight_layout() | |
| save_fig(fig, out, "fig_chamfer_per_class") | |
| def correlation_analysis(df, csv_path: Path, out: Path, methods): | |
| from scipy.stats import spearmanr | |
| det = pd.read_csv(csv_path) | |
| det["key"] = det["class"].map(norm) | |
| d = df.copy() | |
| d["key"] = d["cls"].map(norm) | |
| m = d.merge(det[["method", "key", "score"]], on=["method", "key"]) | |
| if m.empty: | |
| print("[warn] detection CSV could not be matched (check method and class names)") | |
| return | |
| colors = pastel_viridis(len(methods)) | |
| fig, ax = plt.subplots(figsize=(5.5, 4.5)) | |
| lines = [] | |
| for mth, c in zip(methods, colors): | |
| g = m[m.method == mth] | |
| if len(g) < 3: | |
| continue | |
| rho, p = spearmanr(g["chamfer_pct"], g["score"]) | |
| lines.append(f"{mth}: Spearman rho={rho:.3f} (p={p:.3g}, n={len(g)})") | |
| ax.scatter(g["chamfer_pct"], g["score"], color=c, edgecolor="0.3", linewidth=0.5, s=30, | |
| label=f"{mth} (rho={rho:.2f})") | |
| rho, p = spearmanr(m["chamfer_pct"], m["score"]) | |
| lines.append(f"pooled: Spearman rho={rho:.3f} (p={p:.3g}, n={len(m)})") | |
| ax.set_xlabel("Chamfer-L1 [% of CAD diagonal]") | |
| ax.set_ylabel("Detection score") | |
| ax.legend(frameon=False, fontsize=8) | |
| ax.grid(alpha=0.3) | |
| fig.tight_layout() | |
| save_fig(fig, out, "fig_fidelity_vs_detection") | |
| (out / "correlation.txt").write_text("\n".join(lines)) | |
| print("\n".join(lines)) | |
| def cmd_evaluate(args): | |
| rows = [] | |
| for m, k, cp, rp in get_pairs(args): | |
| rp_json = reg_path(args.out, m, k) | |
| if not rp_json.exists(): | |
| print(f"[warn] no registration for {m}/{cp.stem}, skipped") | |
| continue | |
| reg = json.loads(rp_json.read_text()) | |
| T = np.array(reg["T"]) | |
| cad, rec = trimesh.load(cp, process=False), trimesh.load(rp, process=False) | |
| r = evaluate_pair(cad, rec, T, args.n_points, args.seed) | |
| auto = bool(reg.get("auto_scaled", False)) | |
| r.update(method=m, cls=cp.stem, scale=reg["scale"], auto_scaled=auto, manual=bool(reg.get("manual", False)), | |
| scale_err_pct=np.nan if auto else (reg["scale"] - 1) * 100, | |
| scale_err_abs=np.nan if auto else abs(reg["scale"] - 1) * 100, init=reg["init"]) | |
| rows.append(r) | |
| print(f"{m}/{cp.stem}: CD={r['chamfer_pct']:.3f}% HD95={r['hd95_pct']:.3f}% F1={r['f1']:.3f} " | |
| f"s={reg['scale']:.4f}{' [auto-scaled, scale error n/a]' if auto else ''}") | |
| if not rows: | |
| sys.exit("Nothing to evaluate.") | |
| df = pd.DataFrame(rows) | |
| print(f"manually corrected pairs: {int(df['manual'].sum())} of {len(df)}") | |
| args.out.mkdir(parents=True, exist_ok=True) | |
| df.round(5).to_csv(args.out / "metrics_per_class.csv", index=False) | |
| methods = list(dict.fromkeys(df.method)) | |
| md, tex = fmt_table(df, methods) | |
| (args.out / "metrics_summary.md").write_text(md) | |
| (args.out / "metrics_summary.tex").write_text(tex) | |
| print("\n" + md + "\n") | |
| make_plots(df, args.out, methods) | |
| if args.detection_csv: | |
| correlation_analysis(df, args.detection_csv, args.out, methods) | |
| print(f"Results written to {args.out}") | |
| # ---------------------------------------------------------------------------------------------- | |
| # 4) Visualisation helpers: deviation scale, mm axes, vector-PDF renderer | |
| # ---------------------------------------------------------------------------------------------- | |
| AXIS_COLS = [(0.90, 0.20, 0.20), (0.20, 0.75, 0.25), (0.25, 0.45, 0.95)] | |
| def global_dev_max(out: Path, frac: float = 0.02) -> float: | |
| """Deviation colour-scale upper limit [mm], identical for every sample of the database. | |
| Default: `frac` (2 %) of the median CAD OBB diagonal over ALL stored registrations (all methods, | |
| independent of the --methods / --classes filters), rounded to 2 significant digits. | |
| Pass --dev-max-mm explicitly to fix it across runs.""" | |
| ds = [] | |
| for f in (out / "registrations").glob("*/*.json"): | |
| try: | |
| ds.append(float(json.loads(f.read_text())["diag_mm"])) | |
| except Exception: | |
| pass | |
| v = frac * float(np.median(ds)) if ds else 1.0 | |
| return float(f"{v:.2g}") | |
| def heat_colors(dist: np.ndarray, dev_max: float, cmap) -> np.ndarray: | |
| """Map distances [mm] to RGB with a fixed scale 0..dev_max (values above are clipped).""" | |
| return np.asarray(cmap(np.clip(dist / dev_max, 0.0, 1.0)))[:, :3] | |
| def nice_step(span: float, target: int = 5) -> float: | |
| raw = max(span, 1e-9) / target | |
| mag = 10.0 ** np.floor(np.log10(raw)) | |
| cands = np.array([1, 2, 5, 10]) * mag | |
| return float(cands[np.argmin(np.abs(np.log(cands / raw)))]) | |
| def mm_axes_geometry(lo: np.ndarray, hi: np.ndarray, step: float = 0.0): | |
| """Three orthogonal axes with millimetre ticks, starting at the min corner `lo` of the bounding box. | |
| Tick values are distances from that corner (a scale reference), not absolute CAD coordinates. | |
| Returns (segments [(p0, p1, rgb)], labels [(pos, text)], step).""" | |
| ext = np.asarray(hi, float) - np.asarray(lo, float) | |
| step = step if step > 0 else nice_step(float(ext.max())) | |
| tl = 0.025 * float(ext.max()) | |
| E = np.eye(3) | |
| segs, labels = [], [] | |
| for a in range(3): | |
| n = max(1, int(np.ceil(ext[a] / step - 1e-9))) | |
| length = n * step | |
| t = E[(a + 1) % 3] | |
| segs.append((lo, lo + length * E[a], AXIS_COLS[a])) | |
| for k in range(n + 1): | |
| p = lo + k * step * E[a] | |
| segs.append((p, p - tl * t, AXIS_COLS[a])) | |
| labels.append((p - 2.6 * tl * t, f"{k * step:g}")) | |
| labels.append((lo + (length + 0.55 * step) * E[a], f"{'XYZ'[a]} [mm]")) | |
| return segs, labels, step | |
| def project(Pm: np.ndarray, Vm: np.ndarray, X: np.ndarray): | |
| """World points -> (view-space xyz, NDC xyz, in-front mask) using OpenGL-style view/projection.""" | |
| cam = np.c_[X, np.ones(len(X))] @ Vm.T | |
| clip = cam @ Pm.T | |
| w = clip[:, 3] | |
| ok = w > 1e-9 | |
| ndc = clip[:, :3] / np.where(ok, w, 1.0)[:, None] | |
| return cam[:, :3], ndc, ok | |
| def decimate(V: np.ndarray, F: np.ndarray, max_faces: int): | |
| if max_faces <= 0 or len(F) <= max_faces: | |
| return V, F | |
| m = o3d.geometry.TriangleMesh(o3d.utility.Vector3dVector(V), o3d.utility.Vector3iVector(F.astype(np.int32))) | |
| m = m.simplify_quadric_decimation(int(max_faces)) | |
| return np.asarray(m.vertices), np.asarray(m.triangles) | |
| def render_vector_pdf(path: Path, Vm, Pm, meshes, points, axes, bg, cbar, width_in, shade, pt_size): | |
| """Render a scene through the given camera, saving a vector PDF or a 300-DPI PNG. | |
| meshes : list of (V, F, per-vertex RGB) triangles, painter's algorithm (far to near) | |
| points : None or (P, rgb) drawn as tiny triangles, depth-sorted with the meshes | |
| axes : None or (segments, labels) mm axes, drawn on top of the geometry | |
| bg : "black" | "white" | |
| cbar : None or (dev_max_mm, cmap) colour bar in a separate column (view stays 1:1) | |
| shade : 0..1 strength of the headlight shading (0 = flat colours, exactly matching the colour bar) | |
| """ | |
| fg = (1, 1, 1) if bg == "black" else (0, 0, 0) | |
| bgc = (0, 0, 0) if bg == "black" else (1, 1, 1) | |
| aspect = float(Pm[1, 1] / Pm[0, 0]) | |
| xy_l, col_l, z_l = [], [], [] | |
| for V, F, C in meshes: | |
| cam, ndc, ok = project(Pm, Vm, V) | |
| Fk = F[ok[F].all(axis=1)] | |
| if len(Fk) == 0: | |
| continue | |
| a, b, c = cam[Fk[:, 0]], cam[Fk[:, 1]], cam[Fk[:, 2]] | |
| n = np.cross(b - a, c - a) | |
| n /= np.linalg.norm(n, axis=1, keepdims=True) + 1e-12 | |
| ctr = (a + b + c) / 3.0 | |
| vdir = -ctr / (np.linalg.norm(ctr, axis=1, keepdims=True) + 1e-12) | |
| lam = np.abs((n * vdir).sum(1)) | |
| col = C[Fk].mean(axis=1) * ((1 - shade) + shade * lam)[:, None] | |
| q = ndc[Fk] | |
| xy_l.append(np.stack([q[:, :, 0] * aspect, q[:, :, 1]], axis=-1)) | |
| col_l.append(col) | |
| z_l.append(ctr[:, 2]) | |
| if points is not None: | |
| P, c = points | |
| cam, ndc, ok = project(Pm, Vm, P) | |
| cam, ndc = cam[ok], ndc[ok] | |
| x, y, h = ndc[:, 0] * aspect, ndc[:, 1], pt_size / 2.0 | |
| xy_l.append(np.stack([np.stack([x - h, y - h], -1), np.stack([x + h, y - h], -1), | |
| np.stack([x, y + h], -1)], axis=1)) | |
| col_l.append(np.tile(np.asarray(c, float), (len(x), 1))) | |
| z_l.append(cam[:, 2]) | |
| xy, cols, z = np.concatenate(xy_l), np.clip(np.concatenate(col_l), 0, 1), np.concatenate(z_l) | |
| order = np.argsort(z) | |
| extra = 0.24 * width_in if cbar else 0.0 | |
| height_in = width_in / aspect | |
| fig = plt.figure(figsize=(width_in + extra, height_in), facecolor=bgc) | |
| ax = fig.add_axes([0, 0, width_in / (width_in + extra), 1]) | |
| ax.set_xlim(-aspect, aspect) | |
| ax.set_ylim(-1, 1) | |
| ax.axis("off") | |
| ax.add_collection(PolyCollection(xy[order], facecolors=cols[order], edgecolors=cols[order], | |
| linewidths=0.2, antialiaseds=True, zorder=1)) | |
| if axes is not None: | |
| segs, labels = axes | |
| P0 = np.array([s[0] for s in segs]) | |
| P1 = np.array([s[1] for s in segs]) | |
| _, n0, ok0 = project(Pm, Vm, P0) | |
| _, n1, ok1 = project(Pm, Vm, P1) | |
| k = ok0 & ok1 | |
| lines = np.stack([np.c_[n0[:, 0] * aspect, n0[:, 1]], np.c_[n1[:, 0] * aspect, n1[:, 1]]], axis=1)[k] | |
| ax.add_collection(LineCollection(lines, colors=[s[2] for s, kk in zip(segs, k) if kk], | |
| linewidths=1.0, capstyle="round", zorder=5)) | |
| for pos, txt in labels: | |
| _, nd, okp = project(Pm, Vm, np.asarray(pos, float)[None]) | |
| if okp[0]: | |
| ax.text(nd[0, 0] * aspect, nd[0, 1], txt, color=fg, fontsize=12, ha="center", | |
| va="center", zorder=6) | |
| if cbar: | |
| dev_max, cmap = cbar | |
| x0 = (width_in * 1.04) / (width_in + extra) | |
| cax = fig.add_axes([x0, 0.2, 0.025 * width_in / (width_in + extra), 0.6]) | |
| cb = fig.colorbar(cm.ScalarMappable(Normalize(0.0, dev_max), cmap), cax=cax, extend="max") | |
| cb.set_label("Deviation [mm]", color=fg, fontsize=12) | |
| cb.ax.tick_params(color=fg, labelcolor=fg, labelsize=12) | |
| cb.outline.set_edgecolor(fg) | |
| cb.solids.set_rasterized(False) | |
| cb.solids.set_edgecolor("face") | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| # Save PNG directly with Matplotlib at 300 DPI; PDFs retain the original vector output. | |
| if path.suffix.lower() == ".png": | |
| fig.savefig(path, format="png", dpi=300, facecolor=bgc) | |
| else: | |
| fig.savefig(path, format="pdf", facecolor=bgc) | |
| plt.close(fig) | |
| return path | |
| def colorbar_image(dev_max: float, cmap): | |
| """Small raster of the colour bar for the GUI side panel (the PDF contains a true vector colour bar).""" | |
| fig = plt.figure(figsize=(1.7, 3.2), dpi=100, facecolor="#333333") | |
| cax = fig.add_axes([0.2, 0.08, 0.2, 0.84]) | |
| cb = fig.colorbar(cm.ScalarMappable(Normalize(0.0, dev_max), cmap), cax=cax, extend="max") | |
| cb.set_label("Deviation [mm]", color="w", fontsize=8) | |
| cb.ax.tick_params(color="w", labelcolor="w", labelsize=8) | |
| cb.outline.set_edgecolor("w") | |
| fig.canvas.draw() | |
| arr = np.ascontiguousarray(np.asarray(fig.canvas.buffer_rgba())[..., :3]) | |
| plt.close(fig) | |
| return o3d.geometry.Image(arr) | |
| # NEW: standalone colour bar PDF export | |
| def export_colorbar_pdf(path: Path, dev_max: float, cmap, bg="white"): | |
| """Export the deviation colour bar alone as a standalone vector PDF.""" | |
| bgc = "black" if bg == "black" else "white" | |
| fg = "white" if bg == "black" else "black" | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| fig = plt.figure(figsize=(2.0, 4.0), facecolor=bgc) | |
| cax = fig.add_axes([0.30, 0.10, 0.24, 0.80]) | |
| cb = fig.colorbar( | |
| cm.ScalarMappable(Normalize(0.0, dev_max), cmap), | |
| cax=cax, | |
| extend="max", | |
| ) | |
| cb.set_label("Deviation [mm]", color=fg, fontsize=10) | |
| cb.ax.tick_params(color=fg, labelcolor=fg, labelsize=9) | |
| cb.outline.set_edgecolor(fg) | |
| cb.solids.set_edgecolor("face") | |
| fig.savefig( | |
| path, | |
| format="pdf", | |
| facecolor=bgc, | |
| bbox_inches="tight", | |
| pad_inches=0.08, | |
| ) | |
| plt.close(fig) | |
| return path | |
| # ---------------------------------------------------------------------------------------------- | |
| # 5) Interactive viewer (Open3D GUI with buttons, manual flips, ICP refine, save, vector export) | |
| # ---------------------------------------------------------------------------------------------- | |
| STEP_ANGLES = [1, 5, 15, 45, 90] | |
| def cmd_view(args): | |
| import shutil | |
| from open3d.visualization import gui, rendering | |
| scaling = not getattr(args, "rigid", False) | |
| items = [(m, k) for (m, k, _, _) in get_pairs(args) if reg_path(args.out, m, k).exists()] | |
| if not items: | |
| sys.exit("No registrations found. Run `register` first.") | |
| idx = index_meshes(args.out) | |
| colors = pastel_viridis(3) | |
| CAD_COL, REC_COL = colors[0], colors[2] | |
| cmap = plt.get_cmap(args.cmap) | |
| dev_max = args.dev_max_mm if args.dev_max_mm > 0 else global_dev_max(args.out) | |
| print(f"Deviation colour scale: 0 to {dev_max:g} mm, colormap '{args.cmap}', identical for all samples " | |
| f"(use --dev-max-mm {dev_max:g} to keep it fixed across runs)") | |
| pdf_dir = args.pdf_dir or (args.out / "figures") | |
| flags = load_flags(args.out) | |
| cache = {} | |
| st = dict(i=0, after=True, heat=False, cad_mesh=False, axes=True, show_cad=True, | |
| mm=args.mm_axes, cbar=args.colorbar, bg=args.background) | |
| classes = list(dict.fromkeys(k for _, k in items)) | |
| def fg(): | |
| return (1.0, 1.0, 1.0) if st["bg"] == "black" else (0.0, 0.0, 0.0) | |
| def bg_rgba(): | |
| return [0.0, 0.0, 0.0, 1.0] if st["bg"] == "black" else [1.0, 1.0, 1.0, 1.0] | |
| def bak_path(m, k): | |
| return args.out / "registrations_auto" / m / f"{k}.json" | |
| def load(m, k): | |
| if (m, k) not in cache: | |
| cad = trimesh.load(idx[args.cad_folder][k], process=False) | |
| rec = trimesh.load(idx[m][k], process=False) | |
| reg = json.loads(reg_path(args.out, m, k).read_text()) | |
| T = np.array(reg["T"]) | |
| pts = sample(cad, 50000, 0) | |
| cad_leg = o3d.geometry.TriangleMesh(o3d.utility.Vector3dVector(np.asarray(cad.vertices)), | |
| o3d.utility.Vector3iVector(np.asarray(cad.faces).astype(np.int32))) | |
| rc = o3d.t.geometry.RaycastingScene() | |
| rc.add_triangles(o3d.t.geometry.TriangleMesh.from_legacy(cad_leg)) | |
| cache[(m, k)] = dict(cad=cad, rec=rec, T=T.copy(), T_saved=T.copy(), hist=[], reg=reg, | |
| cad_pts=pts, rc=rc, diag=obb_diag(cad), | |
| rec_pts=sample(rec, 30000, 1), cad_pcd=to_pcd(pts[:30000])) | |
| return cache[(m, k)] | |
| def cur(): | |
| return load(*items[st["i"]]) | |
| def quick_chamfer(d, T): | |
| return chamfer_np(apply_T(d["rec_pts"][:5000], T), d["cad_pts"][:5000]) | |
| def dev_dist(d, V): | |
| """Unsigned point-to-surface distance [mm] from points V to the CAD mesh.""" | |
| q = o3d.core.Tensor(np.ascontiguousarray(V, dtype=np.float32)) | |
| return d["rc"].compute_distance(q).numpy().astype(np.float64) | |
| def bounds(d, V): | |
| return np.minimum(V.min(0), d["cad_pts"].min(0)), np.maximum(V.max(0), d["cad_pts"].max(0)) | |
| def rec_vertices(d): | |
| T = d["T"] if st["after"] else np.eye(4) | |
| return apply_T(np.asarray(d["rec"].vertices), T) | |
| def mm_lineset(segs): | |
| pts = np.array([p for s in segs for p in s[:2]], dtype=np.float64) | |
| lines = np.arange(len(pts), dtype=np.int32).reshape(-1, 2) | |
| ls = o3d.geometry.LineSet(o3d.utility.Vector3dVector(pts), o3d.utility.Vector2iVector(lines)) | |
| ls.colors = o3d.utility.Vector3dVector(np.array([s[2] for s in segs], dtype=np.float64)) | |
| return ls, pts | |
| def build(): | |
| d = cur() | |
| V = rec_vertices(d) | |
| rec = o3d.geometry.TriangleMesh(o3d.utility.Vector3dVector(V), | |
| o3d.utility.Vector3iVector(np.asarray(d["rec"].faces).astype(np.int32))) | |
| rec.compute_vertex_normals() | |
| if st["heat"]: | |
| col = heat_colors(dev_dist(d, V), dev_max, cmap) | |
| else: | |
| col = np.tile(REC_COL, (len(V), 1)) | |
| rec.vertex_colors = o3d.utility.Vector3dVector(col) | |
| if st["cad_mesh"]: | |
| cad = o3d.geometry.TriangleMesh(o3d.utility.Vector3dVector(np.asarray(d["cad"].vertices)), | |
| o3d.utility.Vector3iVector(np.asarray(d["cad"].faces).astype(np.int32))) | |
| cad.compute_vertex_normals() | |
| else: | |
| cad = to_pcd(d["cad_pts"][:25000]) | |
| cad.paint_uniform_color(CAD_COL) | |
| tri = o3d.geometry.TriangleMesh.create_coordinate_frame(size=0.35 * d["diag"], | |
| origin=d["cad_pts"].mean(0)) | |
| lo, hi = bounds(d, V) | |
| mm = None | |
| if st["mm"]: | |
| segs, labels, _ = mm_axes_geometry(lo, hi, args.axes_step) | |
| ls, P = mm_lineset(segs) | |
| mm = (ls, labels) | |
| lo, hi = np.minimum(lo, P.min(0)), np.maximum(hi, P.max(0)) | |
| return cad, rec, tri, mm, lo, hi | |
| app = gui.Application.instance | |
| app.initialize() | |
| win = app.create_window("Alignment check and manual correction", 1500, 950) | |
| em = win.theme.font_size | |
| scene = gui.SceneWidget() | |
| scene.scene = rendering.Open3DScene(win.renderer) | |
| scene.scene.set_background(bg_rgba()) | |
| panel = gui.ScrollableVert(int(0.5 * em), gui.Margins(int(em), int(em), int(em), int(em))) | |
| win.add_child(scene) | |
| win.add_child(panel) | |
| mat_mesh = rendering.MaterialRecord() | |
| mat_mesh.shader = "defaultLit" | |
| mat_pts = rendering.MaterialRecord() | |
| mat_pts.shader = "defaultUnlit" | |
| mat_pts.point_size = 1.0 * win.scaling | |
| mat_line = rendering.MaterialRecord() | |
| mat_line.shader = "unlitLine" | |
| mat_line.line_width = 2.0 * win.scaling | |
| labels3d = [] | |
| def on_layout(ctx): | |
| r = win.content_rect | |
| pw = int(20 * em) | |
| scene.frame = gui.Rect(r.x, r.y, r.width - pw, r.height) | |
| panel.frame = gui.Rect(r.get_right() - pw, r.y, pw, r.height) | |
| win.set_on_layout(on_layout) | |
| lbl_pair, lbl_state, lbl_reg = gui.Label(""), gui.Label(""), gui.Label("") | |
| lbl_cd, lbl_dirty, lbl_msg = gui.Label(""), gui.Label(""), gui.Label("") | |
| flag_btn = gui.Button("Flag as bad") | |
| class_combo, angle_combo = gui.Combobox(), gui.Combobox() | |
| cbar_img = gui.ImageWidget(colorbar_image(dev_max, cmap)) | |
| def refresh(reset=False): | |
| m, k = items[st["i"]] | |
| d = cur() | |
| cad, rec, tri, mm, lo, hi = build() | |
| sc = scene.scene | |
| sc.clear_geometry() | |
| for lab in labels3d: | |
| scene.remove_3d_label(lab) | |
| labels3d.clear() | |
| if st["show_cad"]: | |
| sc.add_geometry("cad", cad, mat_mesh if st["cad_mesh"] else mat_pts) | |
| sc.add_geometry("rec", rec, mat_mesh) | |
| if st["axes"]: | |
| sc.add_geometry("axes", tri, mat_mesh) | |
| if mm is not None: | |
| sc.add_geometry("mmaxes", mm[0], mat_line) | |
| for pos, txt in mm[1]: | |
| lab = scene.add_3d_label(np.asarray(pos, dtype=np.float64), txt) | |
| try: | |
| lab.color = gui.Color(*fg(), 1.0) | |
| except Exception: | |
| pass | |
| labels3d.append(lab) | |
| if reset: | |
| bb = o3d.geometry.AxisAlignedBoundingBox(lo, hi) | |
| scene.setup_camera(60.0, bb, bb.get_center()) | |
| cbar_img.visible = bool(st["cbar"]) | |
| dirty = not np.allclose(d["T"], d["T_saved"], atol=1e-9) | |
| lbl_pair.text = f"{m} / {d['reg']['cls']} ({st['i'] + 1}/{len(items)})" | |
| lbl_state.text = "Showing: REGISTERED" if st["after"] else "Showing: RAW (before registration)" | |
| lbl_reg.text = (f"scale {scale_of(d['T']):.4f}{' (auto)' if d['reg'].get('auto_scaled') else ''}, " | |
| f"saved init: {d['reg']['init']}") | |
| lbl_cd.text = f"Chamfer (5k pts): {quick_chamfer(d, d['T']):.3f} mm" | |
| lbl_dirty.text = "UNSAVED changes" if dirty else "Pose matches saved registration" | |
| flag_btn.text = "Unflag (currently FLAGGED)" if f"{m}/{k}" in flags else "Flag as bad" | |
| class_combo.selected_index = classes.index(k) | |
| win.set_needs_layout() | |
| win.post_redraw() | |
| def goto(i, reset=True): | |
| st["i"] = i % len(items) | |
| lbl_msg.text = "" | |
| refresh(reset) | |
| def switch_method(delta): | |
| m, k = items[st["i"]] | |
| ms = list(dict.fromkeys(x[0] for x in items)) | |
| tgt = ms[(ms.index(m) + delta) % len(ms)] | |
| same = [j for j, x in enumerate(items) if x == (tgt, k)] | |
| goto(same[0] if same else next(j for j, x in enumerate(items) if x[0] == tgt)) | |
| def on_class(text, index): | |
| m, _ = items[st["i"]] | |
| target = [j for j, x in enumerate(items) if x == (m, classes[index])] | |
| if target: | |
| goto(target[0]) | |
| # ---- manual correction | |
| def rotate(axis, sign, angle=None): | |
| """Rotate the reconstruction about a CAD-frame axis through its own centroid.""" | |
| d = cur() | |
| ang = (angle if angle is not None else STEP_ANGLES[angle_combo.selected_index]) * sign | |
| c = apply_T(d["rec_pts"], d["T"]).mean(0) | |
| R = Rotation.from_rotvec(np.deg2rad(ang) * np.eye(3)[axis]).as_matrix() | |
| A = np.eye(4) | |
| A[:3, :3] = R | |
| A[:3, 3] = c - R @ c | |
| d["hist"].append(d["T"].copy()) | |
| d["T"] = A @ d["T"] | |
| lbl_msg.text = f"Rotated {ang:+g} deg about {'XYZ'[axis]}" | |
| refresh(False) | |
| def refine(): | |
| d = cur() | |
| c0 = quick_chamfer(d, d["T"]) | |
| s_init = scale_of(d["T"]) | |
| diag = d["diag"] | |
| T2 = icp_multiscale(to_pcd(d["rec_pts"]), d["cad_pcd"], d["T"], | |
| [0.05 * diag, 0.02 * diag, 0.01 * diag, 0.005 * diag], [30, 50, 50, 100], scaling) | |
| if not (0.5 < scale_of(T2) / s_init < 2.0): | |
| lbl_msg.text = "Refinement rejected (scale diverged); pose unchanged" | |
| refresh(False) | |
| return | |
| d["hist"].append(d["T"].copy()) | |
| d["T"] = T2 | |
| lbl_msg.text = f"ICP refine: chamfer {c0:.3f} -> {quick_chamfer(d, T2):.3f} mm" | |
| refresh(False) | |
| def undo(): | |
| d = cur() | |
| if d["hist"]: | |
| d["T"] = d["hist"].pop() | |
| lbl_msg.text = "Undid last step" | |
| else: | |
| lbl_msg.text = "Nothing to undo" | |
| refresh(False) | |
| def revert_saved(): | |
| d = cur() | |
| d["T"] = d["T_saved"].copy() | |
| d["hist"].clear() | |
| lbl_msg.text = "Reverted to saved registration" | |
| refresh(False) | |
| def restore_auto(): | |
| m, k = items[st["i"]] | |
| d = cur() | |
| bp = bak_path(m, k) | |
| src = bp if bp.exists() else reg_path(args.out, m, k) | |
| if src == reg_path(args.out, m, k) and d["reg"].get("manual"): | |
| lbl_msg.text = "No automatic backup found" | |
| refresh(False) | |
| return | |
| d["hist"].append(d["T"].copy()) | |
| d["T"] = np.array(json.loads(src.read_text())["T"]) | |
| lbl_msg.text = "Loaded automatic result (not saved yet)" | |
| refresh(False) | |
| def save(): | |
| m, k = items[st["i"]] | |
| d = cur() | |
| dst, bp = reg_path(args.out, m, k), bak_path(m, k) | |
| if not bp.exists(): | |
| bp.parent.mkdir(parents=True, exist_ok=True) | |
| shutil.copy(dst, bp) | |
| T = d["T"] | |
| reg = dict(d["reg"]) | |
| reg.update(T=T.tolist(), scale=scale_of(T), init="manual", manual=True, | |
| score_mm=float(chamfer_np(apply_T(d["rec_pts"], T), d["cad_pts"][:30000]))) | |
| dst.write_text(json.dumps(reg, indent=1)) | |
| d["reg"], d["T_saved"] = reg, T.copy() | |
| d["hist"].clear() | |
| flags.discard(f"{m}/{k}") | |
| save_flags(args.out, flags) | |
| lbl_msg.text = f"Saved manual registration (chamfer ~{reg['score_mm']:.3f} mm)" | |
| refresh(False) | |
| def on_flag(): | |
| tag = "/".join(items[st["i"]]) | |
| flags.symmetric_difference_update({tag}) | |
| save_flags(args.out, flags) | |
| refresh(False) | |
| # ---- vector PDF export of the exact current view | |
| def export_pdf(): | |
| m, k = items[st["i"]] | |
| d = cur() | |
| cam = scene.scene.camera | |
| Vm = np.asarray(cam.get_view_matrix(), dtype=np.float64) | |
| Pm = np.asarray(cam.get_projection_matrix(), dtype=np.float64) | |
| V_full = rec_vertices(d) | |
| _, nd, ok = project(Pm, Vm, V_full.mean(0, keepdims=True)) | |
| if not ok[0] or np.abs(nd[0, :2]).max() > 2.0: | |
| lbl_msg.text = "Camera matrices look inconsistent with the scene; export aborted" | |
| win.post_redraw() | |
| return | |
| V, F = decimate(V_full, np.asarray(d["rec"].faces), args.pdf_max_faces) | |
| col = heat_colors(dev_dist(d, V), dev_max, cmap) if st["heat"] else np.tile(REC_COL, (len(V), 1)) | |
| meshes, points = [(V, F, col)], None | |
| if st["show_cad"]: | |
| if st["cad_mesh"]: | |
| cV, cF = decimate(np.asarray(d["cad"].vertices), np.asarray(d["cad"].faces), args.pdf_max_faces) | |
| meshes.append((cV, cF, np.tile(CAD_COL, (len(cV), 1)))) | |
| else: | |
| points = (d["cad_pts"][:25000], CAD_COL) | |
| axes_spec = None | |
| if st["mm"]: | |
| lo, hi = bounds(d, V_full) | |
| axes_spec = mm_axes_geometry(lo, hi, args.axes_step)[:2] | |
| name = f"{m}_{d['reg']['cls']}" + ("" if st["after"] else "_raw") + ("_dev" if st["heat"] else "") | |
| lbl_msg.text = "Exporting PDF ..." | |
| win.post_redraw() | |
| path = render_vector_pdf(pdf_dir / f"{name}.pdf", Vm, Pm, meshes, points, axes_spec, st["bg"], | |
| (dev_max, cmap) if (st["cbar"] and st["heat"]) else None, | |
| args.pdf_width_in, args.pdf_shade, args.pdf_point_size) | |
| lbl_msg.text = f"Saved {path}" | |
| win.post_redraw() | |
| # NEW: export the same rendered view directly to PNG using Matplotlib (no PyMuPDF). | |
| def export_png(): | |
| m, k = items[st["i"]] | |
| d = cur() | |
| cam = scene.scene.camera | |
| Vm = np.asarray(cam.get_view_matrix(), dtype=np.float64) | |
| Pm = np.asarray(cam.get_projection_matrix(), dtype=np.float64) | |
| V_full = rec_vertices(d) | |
| _, nd, ok = project(Pm, Vm, V_full.mean(0, keepdims=True)) | |
| if not ok[0] or np.abs(nd[0, :2]).max() > 2.0: | |
| lbl_msg.text = "Camera matrices look inconsistent with the scene; export aborted" | |
| win.post_redraw() | |
| return | |
| V, F = decimate(V_full, np.asarray(d["rec"].faces), args.pdf_max_faces) | |
| col = heat_colors(dev_dist(d, V), dev_max, cmap) if st["heat"] else np.tile(REC_COL, (len(V), 1)) | |
| meshes, points = [(V, F, col)], None | |
| if st["show_cad"]: | |
| if st["cad_mesh"]: | |
| cV, cF = decimate(np.asarray(d["cad"].vertices), np.asarray(d["cad"].faces), args.pdf_max_faces) | |
| meshes.append((cV, cF, np.tile(CAD_COL, (len(cV), 1)))) | |
| else: | |
| points = (d["cad_pts"][:25000], CAD_COL) | |
| axes_spec = None | |
| if st["mm"]: | |
| lo, hi = bounds(d, V_full) | |
| axes_spec = mm_axes_geometry(lo, hi, args.axes_step)[:2] | |
| name = f"{m}_{d['reg']['cls']}" + ("" if st["after"] else "_raw") + ("_dev" if st["heat"] else "") | |
| path = pdf_dir / f"{name}.png" | |
| lbl_msg.text = "Exporting PNG ..." | |
| win.post_redraw() | |
| try: | |
| render_vector_pdf( | |
| path, | |
| Vm, | |
| Pm, | |
| meshes, | |
| points, | |
| axes_spec, | |
| st["bg"], | |
| (dev_max, cmap) if (st["cbar"] and st["heat"]) else None, | |
| args.pdf_width_in, | |
| args.pdf_shade, | |
| args.pdf_point_size, | |
| ) | |
| lbl_msg.text = f"Saved PNG (300 dpi): {path}" | |
| except Exception as e: | |
| lbl_msg.text = f"PNG export failed: {e}" | |
| win.post_redraw() | |
| # NEW: export the current deviation colour bar as a standalone vector PDF. | |
| def export_colorbar(): | |
| m, k = items[st["i"]] | |
| d = cur() | |
| path = pdf_dir / f"{m}_{d['reg']['cls']}_colorbar.pdf" | |
| try: | |
| export_colorbar_pdf( | |
| path, | |
| dev_max, | |
| cmap, | |
| bg=st["bg"], | |
| ) | |
| lbl_msg.text = f"Saved colour bar PDF: {path}" | |
| except Exception as e: | |
| lbl_msg.text = f"Colour bar export failed: {e}" | |
| win.post_redraw() | |
| # ---- widget helpers | |
| def button(text, fn, toggle=False, on=False): | |
| b = gui.Button(text) | |
| if toggle: | |
| b.toggleable = True | |
| b.is_on = on | |
| b.set_on_clicked(lambda: fn(b)) | |
| return b | |
| def row(*widgets): | |
| h = gui.Horiz(int(0.4 * em)) | |
| for w in widgets: | |
| h.add_child(w) | |
| return h | |
| def set_state(key): | |
| def fn(b): | |
| st[key] = b.is_on | |
| refresh(False) | |
| return fn | |
| def set_bg(b): | |
| st["bg"] = "white" if b.is_on else "black" | |
| scene.scene.set_background(bg_rgba()) | |
| refresh(False) | |
| def section(title): | |
| panel.add_fixed(int(0.6 * em)) | |
| panel.add_child(gui.Label(f"--- {title} ---")) | |
| for w in (lbl_pair, lbl_reg, lbl_cd, lbl_state, lbl_dirty, lbl_msg): | |
| panel.add_child(w) | |
| section("Navigate") | |
| for c in classes: | |
| class_combo.add_item(idx[args.cad_folder][c].stem) | |
| class_combo.set_on_selection_changed(on_class) | |
| panel.add_child(class_combo) | |
| panel.add_child(row(button("< Prev class", lambda b: goto(st["i"] - 1)), | |
| button("Next class >", lambda b: goto(st["i"] + 1)))) | |
| panel.add_child(gui.Label("Method (same class)")) | |
| panel.add_child(row(button("< Prev", lambda b: switch_method(-1)), | |
| button("Next >", lambda b: switch_method(1)))) | |
| section("Display") | |
| panel.add_child(button("Registered (on) / raw (off)", set_state("after"), toggle=True, on=True)) | |
| panel.add_child(button("Distance heatmap", set_state("heat"), toggle=True)) | |
| panel.add_child(button("Show CAD", set_state("show_cad"), toggle=True, on=True)) | |
| panel.add_child(button("CAD as solid mesh", set_state("cad_mesh"), toggle=True)) | |
| panel.add_child(button("CAD-frame axes (X red, Y green, Z blue)", set_state("axes"), toggle=True, on=True)) | |
| panel.add_child(button("mm axes with ticks", set_state("mm"), toggle=True, on=st["mm"])) | |
| panel.add_child(button("White background", set_bg, toggle=True, on=(st["bg"] == "white"))) | |
| panel.add_child(button("Show colour bar", set_state("cbar"), toggle=True, on=st["cbar"])) | |
| panel.add_child(button("Reset camera", lambda b: refresh(True))) | |
| panel.add_child(gui.Label(f"Heatmap: fixed scale 0 to {dev_max:g} mm (same for all samples)")) | |
| panel.add_child(cbar_img) | |
| section("Manual correction") | |
| panel.add_child(gui.Label("Flip 180 deg about CAD axis")) | |
| panel.add_child(row(button("Flip X", lambda b: rotate(0, 1, 180)), | |
| button("Flip Y", lambda b: rotate(1, 1, 180)), | |
| button("Flip Z", lambda b: rotate(2, 1, 180)))) | |
| panel.add_child(gui.Label("Step rotation")) | |
| for a in STEP_ANGLES: | |
| angle_combo.add_item(f"{a} deg") | |
| angle_combo.selected_index = 1 | |
| panel.add_child(angle_combo) | |
| for ax, name in enumerate("XYZ"): | |
| panel.add_child(row(button(f"Rot {name} -", lambda b, ax=ax: rotate(ax, -1)), | |
| button(f"Rot {name} +", lambda b, ax=ax: rotate(ax, 1)))) | |
| panel.add_child(button("Refine with ICP from current pose", lambda b: refine())) | |
| panel.add_child(row(button("Undo", lambda b: undo()), | |
| button("Revert to saved", lambda b: revert_saved()))) | |
| panel.add_child(button("Load automatic result", lambda b: restore_auto())) | |
| panel.add_child(button("SAVE corrected registration", lambda b: save())) | |
| section("Export") | |
| panel.add_child(button("Export vector PDF (current view)", lambda b: export_pdf())) | |
| panel.add_child(button("Export PNG (300 dpi, current view)", lambda b: export_png())) | |
| panel.add_child(button("Export colour bar (standalone PDF)", lambda b: export_colorbar())) | |
| section("Validation") | |
| flag_btn.set_on_clicked(on_flag) | |
| panel.add_child(flag_btn) | |
| panel.add_child(gui.Label("Mouse: left rotate, wheel zoom, right/shift pan")) | |
| refresh(True) | |
| app.run() | |
| # ---------------------------------------------------------------------------------------------- | |
| # CLI | |
| # ---------------------------------------------------------------------------------------------- | |
| def add_export_args(p): | |
| p.add_argument("--blender", default="blender", help="Blender executable (default: from PATH)") | |
| p.add_argument("--mm-per-bu", type=float, default=0.0, | |
| help="millimetres per Blender unit; 0 = derive from scene unit scale (metres per BU)") | |
| p.add_argument("--exclude-objects", default="^#Collider", | |
| help="regex of Blender object names to skip (default: physics colliders)") | |
| p.add_argument("--glb-unit-to-mm", type=float, default=1000.0, | |
| help="multiplier from glb/obj units to mm (glTF is metres -> 1000)") | |
| p.add_argument("--jobs", type=int, default=4) | |
| p.add_argument("--force", action="store_true", help="re-export existing .ply files") | |
| def add_reg_args(p): | |
| p.add_argument("--rigid", action="store_true", help="rigid registration only (no scale estimation)") | |
| p.add_argument("--init-scale", choices=["manual", "auto"], default="manual", | |
| help="manual: keep exported scale as start; auto: start from OBB diagonal ratio") | |
| p.add_argument("--auto-scale-methods", nargs="*", default=[], | |
| help="methods whose scale is arbitrary (e.g. glb outputs): start from the OBB diagonal ratio. " | |
| "Pairs with a size ratio outside [0.5, 2] are auto-scaled anyway.") | |
| p.add_argument("--extra-inits", type=int, default=None, help="extra random-rotation starts (default 0, 300 for retry)") | |
| p.add_argument("--retry-flagged", action="store_true", help="only re-register pairs flagged in the viewer") | |
| p.add_argument("--skip-existing", action="store_true") | |
| p.add_argument("--overwrite-manual", action="store_true", | |
| help="allow `register` to overwrite registrations saved from the viewer") | |
| p.add_argument("--seed", type=int, default=0) | |
| def add_eval_args(p): | |
| p.add_argument("--n-points", type=int, default=100000, help="surface samples per mesh for metrics") | |
| p.add_argument("--detection-csv", type=Path, default=None, | |
| help="optional CSV with columns method,class,score for a Spearman correlation analysis") | |
| p.add_argument("--seed", type=int, default=0) if not any(a.dest == "seed" for a in p._actions) else None | |
| def add_view_args(p): | |
| p.add_argument("--rigid", action="store_true", help="ICP refinement in the viewer without scale estimation") | |
| p.add_argument("--background", choices=["black", "white"], default="black", | |
| help="viewer and PDF background (also switchable in the panel)") | |
| p.add_argument("--mm-axes", action="store_true", | |
| help="show three orthogonal millimetre axes with ticks at the min corner of the bounding box " | |
| "(ticks measure distance from that corner); also in the PDF") | |
| p.add_argument("--axes-step", type=float, default=0.0, | |
| help="tick spacing of the mm axes in mm; 0 = automatic round value") | |
| p.add_argument("--colorbar", action="store_true", | |
| help="show the deviation colour bar (side panel in the GUI, vector colour bar in the PDF " | |
| "when the heatmap is active)") | |
| p.add_argument("--dev-max-mm", type=float, default=0.0, | |
| help="upper limit of the deviation colour scale in mm, identical for all samples; " | |
| "0 = 2%% of the median CAD diagonal over all stored registrations (printed at start)") | |
| p.add_argument("--cmap", default="viridis", help="matplotlib colormap of the deviation heatmap") | |
| p.add_argument("--pdf-dir", type=Path, default=None, help="output folder of PDFs (default: <out>/figures)") | |
| p.add_argument("--pdf-width-in", type=float, default=6.0, help="width of the 3D view in the PDF [inch]") | |
| p.add_argument("--pdf-max-faces", type=int, default=150000, | |
| help="decimate meshes above this face count for the PDF (0 = never)") | |
| p.add_argument("--pdf-shade", type=float, default=0.25, | |
| help="headlight shading strength in the PDF, 0 = flat colours that match the colour bar exactly") | |
| p.add_argument("--pdf-point-size", type=float, default=0.006, | |
| help="CAD point size in the PDF as a fraction of the view height") | |
| def main(): | |
| common = argparse.ArgumentParser(add_help=False) | |
| common.add_argument("--root", type=Path, required=True, help="folder with Manual/ and one folder per method") | |
| common.add_argument("--out", type=Path, default=Path("fidelity_out")) | |
| common.add_argument("--cad-folder", default="Manual") | |
| common.add_argument("--methods", nargs="*", default=None, help="restrict to these method folders") | |
| common.add_argument("--classes", nargs="*", default=None, help="restrict to these class names") | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| sub = ap.add_subparsers(dest="cmd", required=True) | |
| add_export_args(sub.add_parser("export", parents=[common])) | |
| add_reg_args(sub.add_parser("register", parents=[common])) | |
| add_eval_args(sub.add_parser("evaluate", parents=[common])) | |
| add_view_args(sub.add_parser("view", parents=[common])) | |
| pa = sub.add_parser("all", parents=[common]) | |
| add_export_args(pa) | |
| add_reg_args(pa) | |
| add_eval_args(pa) | |
| args = ap.parse_args() | |
| if args.cmd in ("export", "all"): | |
| cmd_export(args) | |
| if args.cmd in ("register", "all"): | |
| cmd_register(args) | |
| if args.cmd in ("evaluate", "all"): | |
| cmd_evaluate(args) | |
| if args.cmd == "all": | |
| print("Next: python cad_fidelity.py view --root ... --out ... to validate the alignments visually.") | |
| if args.cmd == "view": | |
| cmd_view(args) | |
| if __name__ == "__main__": | |
| main() | |