| """Visual comparison of reconstructed meshes vs ground truth for held-out cases. |
| |
| Produces, per case, a PNG with GT (grey) and prediction (tooth=blue, canal=red) |
| overlaid, plus an error-colored view (vertices colored by distance to GT). |
| |
| python -m toothcanal.compare --config configs/default.yaml |
| python -m toothcanal.compare --config configs/default.yaml --case 031- |
| """ |
| import os, glob, argparse |
| import numpy as np |
| import torch |
| from .utils import load_config, ensure_dir |
| from .splits import make_split |
| from .models import ImplicitNet |
| from .infer import reconstruct_instance |
| from .evaluate import gt_meshes |
|
|
|
|
| def _load_net(cfg, dev): |
| ckpt = torch.load(os.path.join(cfg["paths"]["out_dir"], "stage2.pt"), |
| map_location=dev) |
| n_lat = ckpt["model"]["latents.weight"].shape[0] |
|
|
| class _N(ImplicitNet): |
| def __init__(s): |
| super().__init__(n_lat, cfg) |
| net = _N().to(dev) |
| net.load_state_dict(ckpt["model"]); net.eval() |
| return net |
|
|
|
|
| def _nearest_dist(pred, gt, n=8000): |
| from scipy.spatial import cKDTree |
| import trimesh |
| pp, _ = trimesh.sample.sample_surface(pred, n) |
| gp, _ = trimesh.sample.sample_surface(gt, n) |
| d, _ = cKDTree(gp).query(pp) |
| return pp, d |
|
|
|
|
| def render_case(net, d, ids, cfg, dev, out_png, do_tto=True, max_teeth=None): |
| import matplotlib |
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
| from mpl_toolkits.mplot3d.art3d import Poly3DCollection |
|
|
| fig = plt.figure(figsize=(16, 6)) |
| axO = fig.add_subplot(131, projection="3d"); axO.set_title("Overlay (grey=GT)") |
| axP = fig.add_subplot(132, projection="3d"); axP.set_title("Prediction") |
| axE = fig.add_subplot(133, projection="3d"); axE.set_title("Error (mm, vs GT)") |
|
|
| allv = [] |
| errs = [] |
| teeth = ids if max_teeth is None else ids[:max_teeth] |
| for iid in teeth: |
| rec = reconstruct_instance(net, d, iid, cfg, dev, do_tto=do_tto) |
| gt_t, gt_c = gt_meshes(d, iid, cfg) |
| if rec is None or rec["tooth"] is None or gt_t is None: |
| continue |
| |
| off = rec["roi"]["lo_world_mm"] |
| pt = rec["tooth"].copy(); pt.vertices += off |
| gt = gt_t.copy(); gt.vertices += off |
| allv.append(pt.vertices) |
| |
| axO.add_collection3d(Poly3DCollection(gt.vertices[gt.faces], facecolor=(.6,.6,.6), |
| alpha=.25, linewidths=0)) |
| axO.add_collection3d(Poly3DCollection(pt.vertices[pt.faces], facecolor=(.2,.4,.8), |
| alpha=.5, linewidths=0)) |
| axP.add_collection3d(Poly3DCollection(pt.vertices[pt.faces], facecolor=(.2,.4,.8), |
| alpha=.7, linewidths=0)) |
| if rec["canal"] is not None: |
| pc = rec["canal"].copy(); pc.vertices += off |
| axP.add_collection3d(Poly3DCollection(pc.vertices[pc.faces], facecolor=(.85,.15,.15), |
| alpha=.95, linewidths=0)) |
| axO.add_collection3d(Poly3DCollection(pc.vertices[pc.faces], facecolor=(.85,.15,.15), |
| alpha=.8, linewidths=0)) |
| |
| pp, dd = _nearest_dist(pt, gt) |
| errs.append(dd) |
| axE.scatter(pp[:,0], pp[:,1], pp[:,2], c=dd, cmap="jet", s=1, vmin=0, vmax=1.0) |
|
|
| if not allv: |
| plt.close(fig); return False |
| V = np.vstack(allv) |
| for ax in (axO, axP, axE): |
| ax.set_xlim(V[:,0].min(), V[:,0].max()) |
| ax.set_ylim(V[:,1].min(), V[:,1].max()) |
| ax.set_zlim(V[:,2].min(), V[:,2].max()) |
| ax.set_axis_off(); ax.view_init(elev=15, azim=-70) |
| if errs: |
| e = np.concatenate(errs) |
| fig.suptitle(f"mean surface error = {e.mean():.3f} mm " |
| f"(blue<{0.0:.1f} red>{1.0:.1f} mm)", fontsize=12) |
| fig.savefig(out_png, dpi=120, bbox_inches="tight"); plt.close(fig) |
| return True |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--config", default="configs/default.yaml") |
| ap.add_argument("--case", default=None) |
| ap.add_argument("--no_tto", action="store_true") |
| ap.add_argument("--max_teeth", type=int, default=None, |
| help="limit teeth per case for a faster preview") |
| args = ap.parse_args() |
| cfg = load_config(args.config) |
| dev = "cuda" if torch.cuda.is_available() else "cpu" |
| net = _load_net(cfg, dev) |
|
|
| _, test = make_split(cfg["paths"]["proc_dir"], cfg) |
| cases = [args.case] if args.case else test |
| out_dir = ensure_dir(os.path.join(cfg["paths"]["out_dir"], "compare")) |
| for cid in cases: |
| d = dict(np.load(os.path.join(cfg["paths"]["proc_dir"], f"{cid}.npz"))) |
| ids = [int(v) for v in np.unique(d["inst"]) if v > 0] |
| out = os.path.join(out_dir, f"{cid}_compare.png") |
| ok = render_case(net, d, ids, cfg, dev, out, do_tto=not args.no_tto, |
| max_teeth=args.max_teeth) |
| print(f"[compare] {cid}: {'wrote '+out if ok else 'no meshes'}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|