| """Shared per-tooth ROI cropping so training / inference / evaluation are consistent.""" |
| import numpy as np |
| from scipy import ndimage as ndi |
|
|
|
|
| def _fit(a, n): |
| out = np.zeros((n, n, n), dtype=a.dtype) |
| s = [min(n, a.shape[k]) for k in range(3)] |
| out[:s[0], :s[1], :s[2]] = a[:s[0], :s[1], :s[2]] |
| return out |
|
|
|
|
| def predicted_instances(d, cfg, dev, stage1_ckpt): |
| """Stage-1-driven instance localization (NO GT). We predict the 4-class map and |
| use the DESCRIPTOR-CORE class (3) -- eroded tooth centers that are spatially |
| separated -- to connected-component into individual teeth, exactly like the |
| 'tooth descriptor' idea in Chen 2025 / Duan 2021. Each core's centroid drives an |
| ROI. Cores are matched to GT instances ONLY for evaluation alignment. |
| |
| Returns inst_pred (full-volume instance map) and match {pred_id -> gt_id}.""" |
| import torch |
| from monai.inferers import sliding_window_inference |
| from .models import get_unet |
| img = d["image"].astype(np.float32) |
| s1 = cfg["stage1"] |
| net = get_unet(s1["num_classes"], tuple(s1["channels"])).to(dev) |
| st = torch.load(stage1_ckpt, map_location=dev) |
| net.load_state_dict(st["model"]); net.eval() |
| with torch.no_grad(): |
| x = torch.from_numpy(img[None, None]).to(dev) |
| logits = sliding_window_inference(x, tuple(s1["patch_size"]), 2, net, overlap=0.25) |
| pred = torch.argmax(logits, 1)[0].cpu().numpy() |
|
|
| use_desc = bool(s1.get("use_descriptor", True)) and (pred == 3).any() |
| seed_mask = (pred == 3) if use_desc else (pred == 1) |
| tooth_pred = (pred == 1) | (pred == 3) |
|
|
| |
| lab, n = ndi.label(seed_mask, structure=np.ones((3, 3, 3))) |
| inst_pred = np.zeros_like(lab, np.int16) |
| match = {} |
| gt_inst = d.get("inst") |
| min_core = int(cfg["stage1"].get("min_core_voxels", 80)) |
| sp = np.asarray(d.get("spacing", np.ones(3)), np.float32) |
| merge_mm = float(cfg["stage1"].get("core_merge_mm", 3.0)) |
|
|
| |
| cores = [] |
| for k in range(1, n + 1): |
| m = (lab == k) |
| if m.sum() < min_core: |
| continue |
| cores.append((k, np.array(ndi.center_of_mass(m)) * sp)) |
|
|
| |
| |
| |
| parent = list(range(len(cores))) |
| def _find(i): |
| while parent[i] != i: |
| parent[i] = parent[parent[i]]; i = parent[i] |
| return i |
| if merge_mm > 0: |
| for i in range(len(cores)): |
| for j in range(i + 1, len(cores)): |
| if np.linalg.norm(cores[i][1] - cores[j][1]) < merge_mm: |
| ri, rj = _find(i), _find(j) |
| if ri != rj: |
| parent[ri] = rj |
| from collections import defaultdict |
| groups = defaultdict(list) |
| for idx, (k, _c) in enumerate(cores): |
| groups[_find(idx)].append(k) |
|
|
| |
| next_id = 1 |
| erode_iter = int(cfg["preprocess"].get("descriptor_erode_iter", 3)) + 2 |
| for klist in groups.values(): |
| core = np.zeros_like(lab, bool) |
| for k in klist: |
| core |= (lab == k) |
| grown = core.copy() |
| for _ in range(erode_iter): |
| grown = ndi.binary_dilation(grown, iterations=1) & tooth_pred |
| cid = next_id; next_id += 1 |
| inst_pred[grown] = cid |
| if gt_inst is not None: |
| ov = gt_inst[grown]; ov = ov[ov > 0] |
| if len(ov) > 0: |
| vals, counts = np.unique(ov, return_counts=True) |
| match[cid] = int(vals[np.argmax(counts)]) |
| return inst_pred, match |
|
|
|
|
| def crop_roi(d, iid, roi_mm, roi_vox, mask_for_center=None, center_mode="com"): |
| """Crop a physical roi_mm cube around tooth `iid`, resample to roi_vox^3. |
| |
| d: processed npz dict with image/inst/cinst/spacing/origin. |
| center_mode: 'com' (center of mass), 'bbox' (bounding-box center, stabler for |
| tilted/multi-root teeth), or 'hybrid' (mean of the two). |
| Returns dict(img, solid, canal, roi_sp, lo_world_mm, boundary_touch, ...) or None. |
| """ |
| img = d["image"]; inst = d["inst"]; cinst = d["cinst"] |
| sp = np.asarray(d["spacing"], dtype=np.float32) |
| origin = np.asarray(d.get("origin", np.zeros(3)), dtype=np.float32) |
|
|
| center_mask = mask_for_center if mask_for_center is not None else (inst == iid) |
| if not center_mask.any(): |
| return None |
| com_mass = np.array(ndi.center_of_mass(center_mask)) |
| if center_mode in ("bbox", "hybrid"): |
| pts = np.argwhere(center_mask) |
| com_box = 0.5 * (pts.min(0) + pts.max(0)) |
| com = com_box if center_mode == "bbox" else 0.5 * (com_mass + com_box) |
| else: |
| com = com_mass |
| half_vox = (roi_mm / 2.0) / sp |
| lo = np.floor(com - half_vox).astype(int) |
| hi = np.ceil(com + half_vox).astype(int) |
| shape = np.array(img.shape) |
| lo_c = np.clip(lo, 0, shape - 1) |
| hi_c = np.clip(hi, 1, shape) |
| sl = tuple(slice(int(a), int(b)) for a, b in zip(lo_c, hi_c)) |
|
|
| img_c = img[sl] |
| solid_c = (inst == iid)[sl] |
| canal_c = (cinst == iid)[sl] |
|
|
| |
| |
| if solid_c.any(): |
| faces = [solid_c[0, :, :], solid_c[-1, :, :], solid_c[:, 0, :], |
| solid_c[:, -1, :], solid_c[:, :, 0], solid_c[:, :, -1]] |
| boundary_touch = float(sum(int(f.sum()) for f in faces) / (solid_c.sum() + 1e-9)) |
| else: |
| boundary_touch = 0.0 |
|
|
| zoom = np.array([roi_vox] * 3) / np.array(img_c.shape) |
| img_r = _fit(ndi.zoom(img_c, zoom, order=1).astype(np.float32), roi_vox) |
| solid_r = _fit(ndi.zoom(solid_c.astype(np.float32), zoom, order=0) > 0.5, roi_vox) |
| canal_r = _fit(ndi.zoom(canal_c.astype(np.float32), zoom, order=0) > 0.5, roi_vox) |
|
|
| roi_sp = np.array([roi_mm / roi_vox] * 3, dtype=np.float32) |
| lo_world_mm = origin + lo_c * sp |
| |
| |
| actual_size_mm = (hi_c - lo_c).astype(np.float32) * sp |
| return dict(img=img_r, solid=solid_r, canal=canal_r, roi_sp=roi_sp, |
| lo_world_mm=lo_world_mm, actual_size_mm=actual_size_mm, |
| boundary_touch=boundary_touch, orig_spacing=sp) |
|
|