"""Boundary-localized segmentation metrics (for the C7 boundary-fidelity analysis). Two standard measures, computed per foreground class then averaged: * Normalized Surface Dice (NSD) @ tol: fraction of pred/gt surface points within `tol` pixels of the other surface (Nikolov et al.); the medical-standard boundary metric. * Boundary-Dice @ tol: Dice between the tol-dilated pred and gt boundaries. Recomputable post-hoc from saved predictions/checkpoints, so adding it never requires retraining (see framework/eval_ckpt.py). """ from __future__ import annotations import numpy as np try: from scipy.ndimage import binary_erosion, binary_dilation, distance_transform_edt _HAVE_SCIPY = True except Exception: # pragma: no cover _HAVE_SCIPY = False def _surface(bin_mask: np.ndarray) -> np.ndarray: return bin_mask ^ binary_erosion(bin_mask) def _nsd_binary(pred: np.ndarray, gt: np.ndarray, tol: float) -> float: sp, sg = _surface(pred), _surface(gt) ssum = sp.sum() + sg.sum() if sp.sum() == 0 and sg.sum() == 0: return 1.0 if ssum == 0: return 0.0 dt_to_gt = distance_transform_edt(~sg) dt_to_pred = distance_transform_edt(~sp) pred_close = (dt_to_gt[sp] <= tol).sum() gt_close = (dt_to_pred[sg] <= tol).sum() return float((pred_close + gt_close) / ssum) def _bdice_binary(pred: np.ndarray, gt: np.ndarray, tol: int) -> float: sp, sg = _surface(pred), _surface(gt) if sp.sum() == 0 and sg.sum() == 0: return 1.0 spd = binary_dilation(sp, iterations=int(tol)) sgd = binary_dilation(sg, iterations=int(tol)) denom = spd.sum() + sgd.sum() if denom == 0: return 0.0 return float(2.0 * (spd & sgd).sum() / denom) def boundary_metrics(pred: np.ndarray, gt: np.ndarray, num_classes: int, tol: float = 2.0) -> dict: """Mean over foreground classes (1..num_classes-1). NaN if scipy missing.""" if not _HAVE_SCIPY: return {"nsd": float("nan"), "boundary_dice": float("nan")} nsds, bdices = [], [] for c in range(1, num_classes): p, g = (pred == c), (gt == c) if g.sum() == 0 and p.sum() == 0: continue nsds.append(_nsd_binary(p, g, tol)) bdices.append(_bdice_binary(p, g, int(round(tol)))) return { "nsd": float(np.mean(nsds)) if nsds else float("nan"), "boundary_dice": float(np.mean(bdices)) if bdices else float("nan"), }