"""Datasets. Stage1Dataset : random 3D patches (image -> 3-class semantic) for coarse segmentation. Stage2Dataset : per-tooth ROI + sampled query points with GT dual-SDF, for the implicit reconstruction core. """ import os import numpy as np from scipy import ndimage as ndi from .geometry import sdf_from_mask, normals_from_sdf, trilinear_sample, \ sample_surface_and_random, canal_centerline def _load(proc_dir, cid, cache): if cid in cache: return cache[cid] d = np.load(os.path.join(proc_dir, f"{cid}.npz")) obj = {k: d[k] for k in d.files} cache[cid] = obj return obj # ----------------------------- STAGE 1 ----------------------------- class Stage1Dataset: def __init__(self, proc_dir, cases, patch=(96, 96, 96), samples_per_volume=4, train=True): self.proc_dir = proc_dir self.cases = cases self.patch = np.array(patch) self.spv = samples_per_volume self.train = train self.cache = {} self.index = [(c, k) for c in cases for k in range(samples_per_volume)] def __len__(self): return len(self.index) def __getitem__(self, i): import torch cid, _ = self.index[i] d = _load(self.proc_dir, cid, self.cache) img, sem = d["image"], d["sem"].astype(np.int64) shape = np.array(img.shape) ps = np.minimum(self.patch, shape) # foreground-biased crop with 50% prob if self.train and sem.any() and np.random.rand() < 0.7: fg = np.argwhere(sem > 0) c = fg[np.random.randint(len(fg))] start = np.clip(c - ps // 2, 0, shape - ps) else: start = (np.random.rand(3) * (shape - ps + 1)).astype(int) sl = tuple(slice(int(s), int(s + p)) for s, p in zip(start, ps)) ip = img[sl][None].astype(np.float32) # [1,X,Y,Z] lp = sem[sl].astype(np.int64) # [X,Y,Z] # pad if needed if tuple(ip.shape[1:]) != tuple(self.patch): pad = [(0, 0)] + [(0, int(self.patch[j] - ip.shape[1 + j])) for j in range(3)] ip = np.pad(ip, pad) lp = np.pad(lp, [(0, int(self.patch[j] - lp.shape[j])) for j in range(3)]) return dict(image=torch.from_numpy(ip), label=torch.from_numpy(lp)) # ----------------------------- STAGE 2 ----------------------------- class Stage2Dataset: """Enumerate (case, tooth-instance) ROIs. Each item yields the ROI image and a fresh batch of sampled query points with GT tooth/canal SDF + normals + occupancy.""" def __init__(self, proc_dir, cases, cfg, train=True): self.proc_dir = proc_dir self.cfg = cfg self.train = train self.cache = {} s2 = cfg["stage2"] self.roi_mm = float(s2["roi_mm"]) self.roi_center = s2.get("roi_center", "com") self.roi_vox = int(s2["roi_vox"]) self.npts = int(s2["points_per_tooth"]) self.near = float(s2["near_surface_ratio"]) self.sigma = float(s2["near_surface_sigma_mm"]) self.canal_frac = float(s2.get("canal_point_frac", 0.4)) self.center_frac = float(s2.get("centerline_frac", 0.0)) self.augment = bool(s2.get("augment", True)) # roi voxel spacing (isotropic) after resampling ROI to roi_vox self.roi_sp = np.array([self.roi_mm / self.roi_vox] * 3, dtype=np.float32) # build global instance list + a global id map (for the latent embedding) self.items = [] for cid in cases: d = _load(proc_dir, cid, self.cache) ids = [int(v) for v in np.unique(d["inst"]) if v > 0] for iid in ids: self.items.append((cid, iid)) self.global_id = {k: n for n, k in enumerate(self.items)} def num_instances(self): return len(self.items) def __len__(self): return len(self.items) def __getitem__(self, i): import torch from .roi import crop_roi cid, iid = self.items[i] d = _load(self.proc_dir, cid, self.cache) crop = crop_roi(d, iid, self.roi_mm, self.roi_vox, center_mode=self.roi_center) if crop is None: return self.__getitem__((i + 1) % len(self)) img_r, solid_r, canal_r = crop["img"], crop["solid"], crop["canal"] # 3D data augmentation (small-data regime: random axis flips + 90-deg rotations). # Applied consistently to image + both masks so SDF/normals stay valid. if self.train and self.augment: for ax in range(3): if np.random.rand() < 0.5: img_r = np.flip(img_r, ax); solid_r = np.flip(solid_r, ax); canal_r = np.flip(canal_r, ax) if np.random.rand() < 0.5: k = np.random.randint(1, 4); pl = tuple(np.random.choice([0, 1, 2], 2, replace=False)) img_r = np.rot90(img_r, k, pl); solid_r = np.rot90(solid_r, k, pl); canal_r = np.rot90(canal_r, k, pl) img_r = np.ascontiguousarray(img_r); solid_r = np.ascontiguousarray(solid_r); canal_r = np.ascontiguousarray(canal_r) sdf_t = sdf_from_mask(solid_r, self.roi_sp) sdf_c = sdf_from_mask(canal_r, self.roi_sp) nrm_t = normals_from_sdf(sdf_t, self.roi_sp) nrm_c = normals_from_sdf(sdf_c, self.roi_sp) # sample query points: tooth surface + canal surface + canal CENTERLINE + random n_canal = int(self.npts * self.canal_frac) if canal_r.any() else 0 n_center = int(self.npts * self.center_frac) if canal_r.any() else 0 n_tooth = self.npts - n_canal - n_center pts_list = [sample_surface_and_random(solid_r, self.roi_sp, n_tooth, self.near, self.sigma)] if n_canal > 0: pts_list.append(sample_surface_and_random(canal_r, self.roi_sp, n_canal, near_ratio=0.9, sigma_mm=self.sigma)) if n_center > 0: skel = canal_centerline(canal_r) sk = np.argwhere(skel) if len(sk) > 0: idx = np.random.randint(0, len(sk), size=n_center) cpts = sk[idx].astype(np.float32) + np.random.normal(0, 0.5, (n_center, 3)) pts_list.append(np.clip(cpts, 0, self.roi_vox - 1)) else: pts_list.append(sample_surface_and_random(canal_r, self.roi_sp, n_center, near_ratio=0.9, sigma_mm=self.sigma)) pts = np.concatenate(pts_list, axis=0) gt_t = trilinear_sample(sdf_t, pts).astype(np.float32) gt_c = trilinear_sample(sdf_c, pts).astype(np.float32) gn_t = trilinear_sample(nrm_t, pts).astype(np.float32) gn_c = trilinear_sample(nrm_c, pts).astype(np.float32) # centerline membership flag (last n_center points are on/near the skeleton) on_center = np.zeros(len(pts), np.float32) if n_center > 0: on_center[-n_center:] = 1.0 # convert voxel coords -> centered mm coords for the network center_vox = (self.roi_vox - 1) / 2.0 coords_mm = (pts - center_vox) * self.roi_sp[None, :] half_mm = self.roi_mm / 2.0 return dict( image=torch.from_numpy(img_r[None].astype(np.float32)), # [1,V,V,V] gid=torch.tensor(self.global_id[(cid, iid)], dtype=torch.long), coords_mm=torch.from_numpy(coords_mm.astype(np.float32)), # [N,3] half_mm=torch.tensor(half_mm, dtype=torch.float32), sdf_tooth=torch.from_numpy(gt_t), # [N] sdf_canal=torch.from_numpy(gt_c), # [N] nrm_tooth=torch.from_numpy(gn_t), # [N,3] nrm_canal=torch.from_numpy(gn_c), # [N,3] on_center=torch.from_numpy(on_center), # [N] case=cid, inst=iid, ) def _fit(a, n): """Force a 3D array to shape (n,n,n) by crop/pad.""" 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