| """Root-canal label cleaning (Stage 0). |
| |
| Implements the three-step cleaning from the report: |
| 1. connected components (26-connectivity) |
| 2. remove specks smaller than a voxel threshold (NOT keep-largest, so real |
| multi-canals in molars survive) |
| 3. morphological closing to bridge artifact-induced gaps (+ optional hole fill) |
| Also returns before/after statistics for the QC table. |
| """ |
| import numpy as np |
| from scipy import ndimage as ndi |
| from skimage import morphology |
|
|
| _FULL26 = np.ones((3, 3, 3), dtype=int) |
|
|
|
|
| def _ball(radius): |
| return morphology.ball(int(radius)) if radius and radius > 0 else None |
|
|
|
|
| def clean_binary(mask, speck_min_voxels=30, closing_radius=1, fill_holes=True): |
| """Clean a single binary structure. Returns (cleaned_mask, stats).""" |
| mask = mask.astype(bool) |
| lab, n = ndi.label(mask, structure=_FULL26) |
| stats = dict(n_components_before=int(n), |
| voxels_before=int(mask.sum())) |
| if n == 0: |
| stats.update(n_components_after=0, voxels_after=0, removed_specks=0, |
| largest_ratio=0.0) |
| return mask, stats |
|
|
| sizes = ndi.sum(np.ones_like(lab), lab, index=np.arange(1, n + 1)) |
| largest = float(sizes.max()) |
| stats["largest_ratio"] = float(largest / max(mask.sum(), 1)) |
|
|
| keep = np.zeros_like(mask) |
| removed = 0 |
| for i, s in enumerate(sizes, start=1): |
| if s >= speck_min_voxels: |
| keep |= (lab == i) |
| else: |
| removed += 1 |
| |
| if not keep.any(): |
| keep = (lab == (1 + int(np.argmax(sizes)))) |
|
|
| if closing_radius and closing_radius > 0: |
| keep = ndi.binary_closing(keep, structure=_ball(closing_radius)) |
| if fill_holes: |
| keep = ndi.binary_fill_holes(keep) |
|
|
| lab2, n2 = ndi.label(keep, structure=_FULL26) |
| stats.update(n_components_after=int(n2), |
| voxels_after=int(keep.sum()), |
| removed_specks=int(removed)) |
| return keep.astype(bool), stats |
|
|
|
|
| def _nearest_body_field(body_map): |
| """For every voxel, the id of the spatially nearest tooth body. |
| Propagates body ids into the pulp space / background via the EDT, so a canal |
| voxel sitting inside a tooth resolves to that tooth's id regardless of how the |
| raw canal label was numbered.""" |
| inds = ndi.distance_transform_edt(body_map == 0, return_indices=True)[1] |
| return body_map[tuple(inds)] |
|
|
|
|
| def build_instances(label_xyz, cfg): |
| """From the raw multi-label volume build per-tooth (body, canal) instances. |
| |
| Returns dict instance_id(1..28) -> {body: bool[x,y,z], canal: bool[x,y,z], |
| tooth_solid: bool[x,y,z]} plus an aggregate cleaning report list. |
| |
| pair_mode (label_scheme.pair_mode): |
| 'geometric' (default) -- assign each canal component to the tooth BODY it |
| physically sits inside (nearest-body), ignoring the raw canal id. |
| Robust to mis-numbered / offset-shifted annotations (the cause of the |
| canal<->tooth ID mismatches found in QC, e.g. cases 032/035/013/014). |
| 'offset' -- legacy: pair canal label i with body label i+pair_offset. |
| """ |
| ls = cfg["label_scheme"] |
| pp = cfg["preprocess"] |
| off = ls["pair_offset"] |
| mode = ls.get("pair_mode", "geometric") |
| report = [] |
| instances = {} |
|
|
| if mode == "offset": |
| for i in range(ls["canal_lo"], ls["canal_hi"] + 1): |
| canal_raw = (label_xyz == i) |
| body_raw = (label_xyz == (i + off)) |
| if not canal_raw.any() and not body_raw.any(): |
| continue |
| canal, st = clean_binary(canal_raw, |
| speck_min_voxels=pp["speck_min_voxels"], |
| closing_radius=pp["closing_radius"], |
| fill_holes=pp["fill_holes"]) |
| st["instance"] = i |
| report.append(st) |
| tooth_solid = ndi.binary_fill_holes((body_raw | canal).astype(bool)) |
| canal = canal & tooth_solid |
| instances[i] = dict(body=body_raw, canal=canal, tooth_solid=tooth_solid) |
| return instances, report |
|
|
| |
| |
| body_map = np.zeros(label_xyz.shape, dtype=np.int16) |
| body_ids = [] |
| for i in range(ls["canal_lo"], ls["canal_hi"] + 1): |
| bmask = (label_xyz == (i + off)) |
| if bmask.any(): |
| body_map[bmask] = i |
| body_ids.append(i) |
| if not body_ids: |
| return instances, report |
|
|
| |
| canal_all = np.zeros(label_xyz.shape, dtype=bool) |
| for i in range(ls["canal_lo"], ls["canal_hi"] + 1): |
| canal_all |= (label_xyz == i) |
| canal_all, _ = clean_binary(canal_all, |
| speck_min_voxels=pp["speck_min_voxels"], |
| closing_radius=pp["closing_radius"], |
| fill_holes=pp["fill_holes"]) |
|
|
| |
| nearest = _nearest_body_field(body_map) |
|
|
| |
| cc, ncc = ndi.label(canal_all, structure=_FULL26) |
| assigned = {i: np.zeros(label_xyz.shape, dtype=bool) for i in body_ids} |
| n_reassigned = 0 |
| n_orphan = 0 |
| for k in range(1, ncc + 1): |
| comp = (cc == k) |
| votes = nearest[comp] |
| votes = votes[votes > 0] |
| if votes.size == 0: |
| n_orphan += int(comp.sum()) |
| continue |
| vals, counts = np.unique(votes, return_counts=True) |
| tgt = int(vals[counts.argmax()]) |
| conf = float(counts.max() / votes.size) |
| if conf < 0.5 or tgt not in assigned: |
| n_orphan += int(comp.sum()) |
| continue |
| assigned[tgt] |= comp |
| |
| raw_here = label_xyz[comp] |
| raw_here = raw_here[(raw_here >= ls["canal_lo"]) & (raw_here <= ls["canal_hi"])] |
| if raw_here.size: |
| raw_id = int(np.bincount(raw_here).argmax()) |
| if raw_id != tgt: |
| n_reassigned += int(comp.sum()) |
|
|
| |
| for i in body_ids: |
| body_raw = (label_xyz == (i + off)) |
| canal = assigned[i] |
| tooth_solid = ndi.binary_fill_holes((body_raw | canal).astype(bool)) |
| canal = canal & tooth_solid |
| instances[i] = dict(body=body_raw, canal=canal, tooth_solid=tooth_solid) |
|
|
| report.append(dict(pairing="geometric", n_components=int(ncc), |
| voxels_reassigned=int(n_reassigned), |
| voxels_orphaned=int(n_orphan), |
| n_instances=len(body_ids))) |
| return instances, report |
|
|