| """Stage 0 preprocessing: per case, produce a compact processed bundle: |
| - image (normalized, [x,y,z] float32) at working spacing |
| - sem (0 bg / 1 tooth-solid / 2 canal) for Stage-1 segmentation |
| - inst (tooth instance id 0..28, from tooth_solid) for Stage-2 ROI cropping |
| - cinst (canal instance id 0..28) |
| - cleaning report (json) for the QC before/after table |
| |
| Run: |
| python -m toothcanal.preprocess --config configs/default.yaml |
| """ |
| import os, argparse |
| import numpy as np |
| from tqdm import tqdm |
| from .utils import (load_config, ensure_dir, load_nii, resample_to_spacing, |
| read_json, write_json) |
| from .cleaning import build_instances |
|
|
|
|
| def normalize_image(img, clip): |
| img = np.clip(img, clip[0], clip[1]).astype(np.float32) |
| lo, hi = float(img.min()), float(img.max()) |
| if hi - lo < 1e-5: |
| return np.zeros_like(img) |
| return (img - lo) / (hi - lo) |
|
|
|
|
| def _fit_to_shape(arr, shape): |
| """Crop or zero-pad a label array to an exact target shape.""" |
| out = np.zeros(shape, dtype=arr.dtype) |
| s = [min(shape[k], arr.shape[k]) for k in range(3)] |
| out[:s[0], :s[1], :s[2]] = arr[:s[0], :s[1], :s[2]] |
| return out |
|
|
|
|
| def _resample_label_to_reference(lab, lmeta, ref_img, ref_meta): |
| """Resample a label volume onto the reference image's exact voxel grid using |
| SimpleITK (nearest neighbor), so label and image align even when the |
| annotation was made at a different resolution.""" |
| import SimpleITK as sitk |
| lab_t = np.transpose(lab, (2, 1, 0)) |
| li = sitk.GetImageFromArray(lab_t) |
| li.SetSpacing(tuple(float(s) for s in lmeta["spacing"])) |
| li.SetOrigin(tuple(float(o) for o in lmeta["origin"])) |
| li.SetDirection(tuple(float(d) for d in lmeta["direction"])) |
|
|
| ref_t = np.transpose(ref_img, (2, 1, 0)) |
| ri = sitk.GetImageFromArray(ref_t) |
| ri.SetSpacing(tuple(float(s) for s in ref_meta["spacing"])) |
| ri.SetOrigin(tuple(float(o) for o in ref_meta["origin"])) |
| ri.SetDirection(tuple(float(d) for d in ref_meta["direction"])) |
|
|
| out = sitk.Resample(li, ri, sitk.Transform(), sitk.sitkNearestNeighbor, 0, |
| li.GetPixelID()) |
| o = sitk.GetArrayFromImage(out) |
| return np.transpose(o, (2, 1, 0)).astype(np.int16) |
|
|
|
|
| def process_case(cid, info, cfg): |
| from .assemble import assemble_label |
| pp = cfg["preprocess"] |
| img, imeta = load_nii(info["image"]) |
| lab, lmeta = load_nii(info["label"]) |
| lab = np.rint(lab).astype(np.int16) |
|
|
| |
| lab, status = assemble_label(lab, info.get("num", -1), cfg) |
| if status == "canal_only": |
| print(f"[preprocess] SKIP {cid}: only canal labels, no tooth labels found " |
| f"(drop tooth nii into paths.extra_tooth_dir).") |
| return None |
|
|
| |
| |
| if lab.shape != img.shape: |
| lab = _resample_label_to_reference(lab, lmeta, img, imeta) |
|
|
| |
| img, imeta2 = resample_to_spacing(img, imeta, pp["spacing"], is_label=False) |
| lab, _ = resample_to_spacing(lab, imeta, pp["spacing"], is_label=True) |
| lab = np.rint(lab).astype(np.int16) |
| imeta = imeta2 |
|
|
| |
| if lab.shape != img.shape: |
| lab = _fit_to_shape(lab, img.shape) |
|
|
| img = normalize_image(img, pp["clip_hu"]) |
|
|
| instances, report = build_instances(lab, cfg) |
|
|
| sem = np.zeros(img.shape, dtype=np.uint8) |
| inst = np.zeros(img.shape, dtype=np.uint8) |
| cinst = np.zeros(img.shape, dtype=np.uint8) |
| desc = np.zeros(img.shape, dtype=np.uint8) |
| from scipy import ndimage as _ndi |
| erode_iter = int(cfg["preprocess"].get("descriptor_erode_iter", 3)) |
| for i, d in instances.items(): |
| sem[d["tooth_solid"]] = 1 |
| inst[d["tooth_solid"]] = i |
| sem[d["canal"]] = 2 |
| cinst[d["canal"]] = i |
| |
| core = _ndi.binary_erosion(d["tooth_solid"], iterations=erode_iter) |
| if not core.any(): |
| core = d["tooth_solid"] |
| desc[core] = i |
| |
| sem[desc > 0] = 3 |
|
|
| out_dir = ensure_dir(cfg["paths"]["proc_dir"]) |
| np.savez_compressed( |
| os.path.join(out_dir, f"{cid}.npz"), |
| image=img.astype(np.float32), |
| sem=sem, inst=inst, cinst=cinst, desc=desc, |
| spacing=np.array(imeta["spacing"], dtype=np.float32), |
| origin=np.array(imeta["origin"], dtype=np.float32), |
| n_instances=len(instances), |
| ) |
| return dict(case=cid, n_instances=len(instances), cleaning=report, |
| status=status, shape=list(img.shape)) |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--config", default="configs/default.yaml") |
| ap.add_argument("--limit", type=int, default=0, help="process only first N (debug)") |
| ap.add_argument("--force", action="store_true", |
| help="reprocess cases even if their .npz already exists") |
| args = ap.parse_args() |
| cfg = load_config(args.config) |
|
|
| manifest = read_json(os.path.join(cfg["paths"]["raw_dir"], "manifest.json")) |
| items = list(manifest.items()) |
| if args.limit: |
| items = items[:args.limit] |
|
|
| ensure_dir(cfg["paths"]["proc_dir"]) |
| if not args.force: |
| before = len(items) |
| items = [(cid, info) for cid, info in items |
| if not os.path.exists(os.path.join(cfg["paths"]["proc_dir"], f"{cid}.npz"))] |
| skipped = before - len(items) |
| if skipped: |
| print(f"[preprocess] skipping {skipped} already-processed case(s); " |
| f"will process {len(items)}.") |
| summary = [] |
| for cid, info in tqdm(items, desc="preprocess"): |
| try: |
| r = process_case(cid, info, cfg) |
| if r is not None: |
| summary.append(r) |
| except Exception as e: |
| print(f"[preprocess] FAILED {cid}: {e}") |
| write_json(summary, os.path.join(cfg["paths"]["proc_dir"], "preprocess_report.json")) |
|
|
| |
| nb = na = vb = va = specks = 0 |
| reassigned = orphaned = ncomp = geo_cases = 0 |
| for s in summary: |
| for c in s["cleaning"]: |
| if "pairing" in c: |
| reassigned += c.get("voxels_reassigned", 0) |
| orphaned += c.get("voxels_orphaned", 0) |
| ncomp += c.get("n_components", 0) |
| geo_cases += 1 |
| else: |
| nb += c.get("n_components_before", 0); na += c.get("n_components_after", 0) |
| vb += c.get("voxels_before", 0); va += c.get("voxels_after", 0) |
| specks += c.get("removed_specks", 0) |
| if geo_cases: |
| print("\n========== canal<->tooth geometric re-pairing ==========") |
| print(f"cases re-paired: {geo_cases} | canal components: {ncomp}") |
| print(f"voxels re-assigned to correct tooth: {reassigned} | orphaned/dropped: {orphaned}") |
| print("========================================================") |
| if vb: |
| print("\n========== canal cleaning (before / after) ==========") |
| print(f"components: {nb} -> {na} (removed {specks} specks)") |
| print(f"voxels retained: {100.0 * va / vb:.2f}% (lost {100.0 * (vb - va) / vb:.2f}%)") |
| print("=====================================================") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|