"""Export predictions as a single .nii.gz label volume per test case, aligned to the processed CBCT, so you can open it in ITK-SNAP ON TOP of the image and scroll through slices (canal = 1..28, tooth body = 29..56), exactly like the GT labels. python -m toothcanal.export_nifti --config configs/default.yaml Outputs, per test case, in outputs/nifti/: _image.nii.gz the (normalized) CBCT used _pred_label.nii.gz predicted labels (open as 'Segmentation' in ITK-SNAP) _gt_label.nii.gz ground-truth labels (for side-by-side comparison) """ import os, argparse import numpy as np import torch from scipy import ndimage as ndi from .utils import load_config, ensure_dir, save_nii from .splits import make_split from .models import ImplicitNet from .infer import reconstruct_instance 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 export_case(cfg, net, cid, dev): d = dict(np.load(os.path.join(cfg["paths"]["proc_dir"], f"{cid}.npz"))) img = d["image"].astype(np.float32) sp = d["spacing"].astype(np.float32) origin = d.get("origin", np.zeros(3)).astype(np.float32) full_shape = img.shape pred = np.zeros(full_shape, np.int16) gt = np.zeros(full_shape, np.int16) # GT directly from processed volumes inst = d["inst"]; cinst = d["cinst"] gt[inst > 0] = inst[inst > 0].astype(np.int16) + 28 # body 29..56 gt[cinst > 0] = cinst[cinst > 0].astype(np.int16) # canal 1..28 ids = [int(v) for v in np.unique(inst) if v > 0] for iid in ids: rec = reconstruct_instance(net, d, iid, cfg, dev, do_tto=False) if rec is None: continue roi = rec["roi"] g = rec["grid"] lo_world = roi["lo_world_mm"] # per-axis grid spacing from the ACTUAL physical extent the ROI covered # (handles teeth clipped at the volume border, which previously stamped wrong). actual = roi.get("actual_size_mm", None) if actual is None: actual = np.array([cfg["stage2"]["roi_mm"]] * 3, np.float32) roi_grid_sp = actual / g for name, occ, value in [("tooth", rec["occ_tooth"], iid + 28), ("canal", rec["occ_canal"], iid)]: pts = np.argwhere(occ > 0) if len(pts) == 0: continue world = lo_world[None, :] + pts * roi_grid_sp[None, :] vox = np.round((world - origin[None, :]) / sp[None, :]).astype(int) ok = np.all((vox >= 0) & (vox < np.array(full_shape)), axis=1) vox = vox[ok] if len(vox) == 0: continue if name == "canal": pred[vox[:, 0], vox[:, 1], vox[:, 2]] = value else: cur = pred[vox[:, 0], vox[:, 1], vox[:, 2]] vv = vox[cur == 0] pred[vv[:, 0], vv[:, 1], vv[:, 2]] = value meta = dict(spacing=sp, origin=origin, direction=np.eye(3).flatten()) out_dir = ensure_dir(os.path.join(cfg["paths"]["out_dir"], "nifti")) save_nii(img, meta, os.path.join(out_dir, f"{cid}_image.nii.gz")) save_nii(pred, meta, os.path.join(out_dir, f"{cid}_pred_label.nii.gz")) save_nii(gt, meta, os.path.join(out_dir, f"{cid}_gt_label.nii.gz")) print(f"[nifti] {cid}: wrote image + pred_label + gt_label to {out_dir}") def main(): ap = argparse.ArgumentParser() ap.add_argument("--config", default="configs/default.yaml") ap.add_argument("--case", default=None) 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 for cid in cases: export_case(cfg, net, cid, dev) if __name__ == "__main__": main()