"""2.5D tri-planar slice extraction from processed 3D volumes. From each normalized volume we take 3 planes (axial, coronal, sagittal) x 9 slices at depth fractions 30..70%, giving 27 slices per subject. Each slice is resized to 224x224 and saved as float16 .npy. The channel dimension (3, for pretrained CNN compatibility) is added at load time, not stored, to save disk. Depth fractions are computed on the *cropped-normalized* volume that preprocess_3d produced (background already trimmed), so 50% lands near brain center. """ from __future__ import annotations import argparse from pathlib import Path import numpy as np from scipy.ndimage import zoom ROOT = Path(__file__).resolve().parents[3] PLANES = ("axial", "coronal", "sagittal") DEPTH_FRACTIONS = (0.30, 0.35, 0.40, 0.45, 0.50, 0.55, 0.60, 0.65, 0.70) SLICE_SIZE = 224 # volume axes after as_closest_canonical (RAS): 0=L-R (sagittal), 1=P-A (coronal), # 2=I-S (axial). A slice through an axis shows the *other* two dims. PLANE_AXIS = {"sagittal": 0, "coronal": 1, "axial": 2} def _resize2d(sl: np.ndarray, size: int = SLICE_SIZE) -> np.ndarray: factors = [size / sl.shape[0], size / sl.shape[1]] out = zoom(sl, factors, order=1) out = out[:size, :size] pad = [(0, size - out.shape[0]), (0, size - out.shape[1])] if pad[0][1] or pad[1][1]: out = np.pad(out, pad) return out.astype(np.float16) def extract_slices(vol: np.ndarray) -> dict[str, np.ndarray]: """Return {plane: (9, 224, 224) float16} for one volume.""" out = {} for plane, axis in PLANE_AXIS.items(): n = vol.shape[axis] slabs = [] for frac in DEPTH_FRACTIONS: idx = int(round(frac * (n - 1))) sl = np.take(vol, idx, axis=axis) slabs.append(_resize2d(sl)) out[plane] = np.stack(slabs) # (9, 224, 224) return out def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--subjects_csv", default="data/metadata/subjects_clean.csv") ap.add_argument("--vol_dir", default="data/processed_3d/cnn3d", help="which processed-3d target to slice from (uses 128^3)") ap.add_argument("--out_root", default="data/processed_2d") ap.add_argument("--limit", type=int, default=0) args = ap.parse_args() import pandas as pd df = pd.read_csv(args.subjects_csv) if args.limit: df = df.head(args.limit) vol_dir = Path(args.vol_dir) out_root = Path(args.out_root) n_ok = 0 for _, row in df.iterrows(): sid = row["subject_id"] vpath = vol_dir / f"{sid}.npy" if not vpath.exists(): print(f"MISS volume for {sid}") continue vol = np.load(vpath) slices = extract_slices(vol) for plane, arr in slices.items(): d = out_root / sid / plane d.mkdir(parents=True, exist_ok=True) np.save(d / "slices.npy", arr) n_ok += 1 if n_ok % 25 == 0: print(f" sliced {n_ok}/{len(df)}") print(f"done: {n_ok}/{len(df)} subjects -> {out_root}") if __name__ == "__main__": main()