"""Export ground-truth meshes (tooth + canal) for the held-out test cases by running marching cubes directly on the CLEANED label volume in WORLD coords. This lets you compare GT vs prediction as two separate assembled scenes. python -m toothcanal.export_gt --config configs/default.yaml """ import os, argparse import numpy as np from .utils import load_config, ensure_dir from .splits import make_split from .geometry import sdf_from_mask, marching_cubes_to_mesh def main(): ap = argparse.ArgumentParser() ap.add_argument("--config", default="configs/default.yaml") args = ap.parse_args() cfg = load_config(args.config) _, test = make_split(cfg["paths"]["proc_dir"], cfg) out_dir = ensure_dir(os.path.join(cfg["paths"]["out_dir"], "gt_meshes")) for cid in test: d = dict(np.load(os.path.join(cfg["paths"]["proc_dir"], f"{cid}.npz"))) inst = d["inst"]; cinst = d["cinst"] sp = d["spacing"].astype(np.float32) origin = d.get("origin", np.zeros(3)).astype(np.float32) ids = [int(v) for v in np.unique(inst) if v > 0] print(f"[gt] {cid}: {len(ids)} teeth") for iid in ids: tooth_mask = (inst == iid) canal_mask = (cinst == iid) for name, mask in [("tooth", tooth_mask), ("canal", canal_mask)]: if not mask.any(): continue # crop to bbox + small pad to keep MC fast ax = np.argwhere(mask) lo = ax.min(0) - 2; hi = ax.max(0) + 3 lo = np.maximum(lo, 0); hi = np.minimum(hi, mask.shape) sl = tuple(slice(int(a), int(b)) for a, b in zip(lo, hi)) sdf = sdf_from_mask(mask[sl], sp) mesh = marching_cubes_to_mesh(sdf, 0.0, sp) if mesh is None: continue # shift to world coords mesh.vertices += (origin + lo * sp)[None, :] mesh.export(os.path.join(out_dir, f"{cid}_t{iid:02d}_{name}_GT.stl")) print(f"[gt] written GT meshes to {out_dir}") if __name__ == "__main__": main()