cbct / pre /code /assemble.py
JulianHJR's picture
Add files using upload-large-folder tool
08764e9 verified
Raw
History Blame Contribute Delete
6.12 kB
"""Assemble a unified label volume (canal = 1..28, tooth body = 29..56) per case.
Some cases (e.g. 21-30) ship with ONLY the canal/pulp annotation; their tooth
labels are supplied separately and dropped into paths.extra_tooth_dir. This module
detects whether a case already has tooth-body labels; if not, it loads the
supplementary tooth label and merges it.
Auto-detected supplementary-tooth schemes:
* values in 29..56 -> used as tooth-body directly
* values in 1..28 -> per-tooth instances, mapped to body = id + 28
* binary {0,1} -> components matched to the nearest canal centroid
The final volume keeps canal voxels as 1..28 and body voxels as 29..56 (disjoint:
the canal cavity is carved out of the solid tooth), matching the 31-35 scheme.
"""
import os, glob
import numpy as np
from scipy import ndimage as ndi
from .utils import load_nii, numeric_id
_FULL26 = np.ones((3, 3, 3), int)
def find_extra_tooth(case_num, extra_dir):
"""Locate a supplementary tooth-label file for a given case number.
Matches several common naming conventions. We scan ALL numeric runs in the
filename and accept one that lies in the valid case range (1..40) and equals
`case_num`. Example: `0300316ok.nii.gz` -> first runs are 0300316; the
largest valid sub-run is 30 (leading "030" -> int 30).
"""
import re
if not extra_dir or not os.path.isdir(extra_dir):
return None
cands = glob.glob(os.path.join(extra_dir, "**", "*.nii.gz"), recursive=True)
matches = []
for p in cands:
base = os.path.basename(p)
# collect every numeric run AND every plausible 2-3 digit sub-run
runs = re.findall(r"\d+", base)
plausible = set()
for r in runs:
# full run
n = int(r)
if 1 <= n <= 40:
plausible.add(n)
# plausible 2-3 digit sub-windows (handles "0300316" -> 30, 300)
for w in (2, 3):
for i in range(len(r) - w + 1):
n = int(r[i:i + w])
if 1 <= n <= 40:
plausible.add(n)
if case_num in plausible:
matches.append(p)
if matches:
# if multiple match (e.g. zzz28.nii.gz and zzz28 (6).nii.gz), pick the largest
return max(matches, key=lambda p: os.path.getsize(os.path.realpath(p)))
return None
def _map_tooth_to_body(tooth, canal, ls):
"""Return a body-label volume in 29..56 from an arbitrary tooth annotation."""
body = np.zeros_like(tooth, dtype=np.int16)
vals = np.unique(tooth[tooth > 0])
off = ls["pair_offset"]
if vals.size == 0:
return body
if vals.min() >= ls["body_lo"] and vals.max() <= ls["body_hi"]:
return tooth.astype(np.int16) # already body ids
if vals.max() <= ls["canal_hi"]:
m = tooth > 0
body[m] = tooth[m].astype(np.int16) + off # 1..28 -> 29..56
return body
if set(vals.tolist()) <= {1}: # binary -> match canals
lab, n = ndi.label(tooth > 0, structure=_FULL26)
for k in range(1, n + 1):
comp = lab == k
cen = np.array(ndi.center_of_mass(comp))
# nearest canal instance centroid
best, bestd = None, 1e18
for cid in range(ls["canal_lo"], ls["canal_hi"] + 1):
cm = canal == cid
if not cm.any():
continue
d = np.linalg.norm(np.array(ndi.center_of_mass(cm)) - cen)
if d < bestd:
bestd, best = d, cid
if best is not None:
body[comp] = best + off
return body
# fallback: relabel components sequentially into body range
lab, n = ndi.label(tooth > 0, structure=_FULL26)
for k in range(1, min(n, ls["n_teeth"]) + 1):
body[lab == k] = ls["body_lo"] + (k - 1)
return body
def assemble_label(primary_label, case_num, cfg):
"""Return (label_volume, status). status in
{'complete', 'extra_override', 'merged', 'canal_only'}.
Logic:
1. If `primary_label` already has tooth-body labels (29..56) AND no extra
file is provided, use it as-is.
2. If an extra file is provided in `extra_tooth_dir`, inspect it:
- if it already contains BOTH canal (1..28) and body (29..56) labels
=> it's a complete annotation, OVERRIDE the primary label with it.
- else (tooth-only / 1..28 / binary) => merge it with the primary canal.
3. If nothing usable is provided and the primary lacks body labels, signal
'canal_only' so preprocessing skips the case with a clear warning.
"""
ls = cfg["label_scheme"]
has_body = ((primary_label >= ls["body_lo"]) &
(primary_label <= ls["body_hi"])).any()
extra_path = find_extra_tooth(case_num, cfg["paths"].get("extra_tooth_dir"))
# case 1: primary already complete, no extra
if has_body and extra_path is None:
return primary_label.astype(np.int16), "complete"
# case 2: an extra label was provided
if extra_path is not None:
extra, _ = load_nii(extra_path)
extra = np.rint(extra).astype(np.int16)
ex_has_canal = ((extra >= ls["canal_lo"]) & (extra <= ls["canal_hi"])).any()
ex_has_body = ((extra >= ls["body_lo"]) & (extra <= ls["body_hi"])).any()
if ex_has_canal and ex_has_body:
return extra, "extra_override" # complete -> override
# otherwise treat extra as tooth-only and merge with primary canal
canal = primary_label.astype(np.int16)
body = _map_tooth_to_body(extra, canal, ls)
merged = np.zeros_like(canal, dtype=np.int16)
merged[body > 0] = body[body > 0]
cmask = (canal >= ls["canal_lo"]) & (canal <= ls["canal_hi"])
merged[cmask] = canal[cmask] # canal carves cavity
return merged, "merged"
# case 3: nothing usable
return primary_label.astype(np.int16), "canal_only"