"""3D preprocessing: OASIS-1 Analyze volume -> normalized .npy. Pipeline per subject (one volume, the atlas-registered brain-masked gain-field- corrected average): read Analyze (.hdr/.img) -> canonical orientation -> nonzero bounding-box crop -> percentile clip (0.5-99.5 on brain voxels) -> z-score on brain -> resize to target. Two targets are written: - 128^3 for 3D CNN (resnet3d) - 96x112x112 for 3D transformer/hybrid (swin3d, hcct, vswin_lite) Saved as float32 .npy under processed_3d//.npy. """ from __future__ import annotations import argparse from pathlib import Path import nibabel as nib import numpy as np from scipy.ndimage import zoom TARGETS = { "cnn3d": (128, 128, 128), "tf3d": (96, 112, 112), } def load_analyze(hdr_path: Path) -> np.ndarray: """Load an Analyze/NIfTI volume as float32, reoriented to canonical (RAS).""" img = nib.load(str(hdr_path)) img = nib.as_closest_canonical(img) # consistent orientation across subjects arr = np.asanyarray(img.dataobj).astype(np.float32) arr = np.squeeze(arr) # OASIS T88 volumes carry a trailing singleton axis return arr def nonzero_bbox_crop(vol: np.ndarray) -> np.ndarray: mask = vol > 0 if not mask.any(): return vol coords = np.array(np.nonzero(mask)) lo = coords.min(axis=1) hi = coords.max(axis=1) + 1 return vol[lo[0]:hi[0], lo[1]:hi[1], lo[2]:hi[2]] def clip_and_zscore(vol: np.ndarray) -> np.ndarray: brain = vol[vol > 0] if brain.size == 0: return vol lo, hi = np.percentile(brain, [0.5, 99.5]) vol = np.clip(vol, lo, hi) brain = vol[vol > 0] mu, sd = brain.mean(), brain.std() if sd < 1e-6: sd = 1.0 out = (vol - mu) / sd out[vol <= 0] = 0.0 # keep background at 0 after normalization return out.astype(np.float32) def resize_to(vol: np.ndarray, shape: tuple[int, int, int]) -> np.ndarray: factors = [s / v for s, v in zip(shape, vol.shape)] out = zoom(vol, factors, order=1) # trilinear # guard against off-by-one from rounding out = out[: shape[0], : shape[1], : shape[2]] pad = [(0, s - o) for s, o in zip(shape, out.shape)] if any(p[1] > 0 for p in pad): out = np.pad(out, pad) return out.astype(np.float32) def preprocess_one(hdr_path: Path) -> dict[str, np.ndarray]: vol = load_analyze(hdr_path) vol = nonzero_bbox_crop(vol) vol = clip_and_zscore(vol) return {name: resize_to(vol, shape) for name, shape in TARGETS.items()} def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--subjects_csv", default="data/metadata/subjects_clean.csv") ap.add_argument("--out_root", default="data/processed_3d") ap.add_argument("--limit", type=int, default=0, help="process only first N (debug)") args = ap.parse_args() import pandas as pd df = pd.read_csv(args.subjects_csv) if args.limit: df = df.head(args.limit) out_root = Path(args.out_root) for name in TARGETS: (out_root / name).mkdir(parents=True, exist_ok=True) n_ok = 0 for _, row in df.iterrows(): sid = row["subject_id"] hdr = Path(row["volume_path"]) try: outs = preprocess_one(hdr) except Exception as e: # noqa: BLE001 - report and continue print(f"FAIL {sid}: {e}") continue for name, arr in outs.items(): np.save(out_root / name / f"{sid}.npy", arr) n_ok += 1 if n_ok % 25 == 0: print(f" processed {n_ok}/{len(df)}") print(f"done: {n_ok}/{len(df)} volumes -> {out_root}") if __name__ == "__main__": main()