""" preprocess_ucsf.py Adapts the repo's 1_registration.py + 2_cutbackground.py pipeline to the UCSF-PDGM file naming you actually have (T1c, T2, FLAIR, tumor_segmentation). Pipeline per subject (matches the paper's described preprocessing): 1. Register T1c -> SRI24 atlas (Affine) 2. Register T2 -> registered T1c (Affine) [fresh registration, like the repo script] 3. Register FLAIR -> registered T1c (Affine) 4. Warp tumor_segmentation using T1c's transform (nearestNeighbor -- masks must NOT be intensity-registered, they ride along on T1c's transform) 5. Crop to combined nonzero bounding box (T1c+T2+FLAIR), then zero-pad to (160, 192, 160) This is SLOW (ANTs registration is CPU-bound). Test on a handful of subjects first with LIMIT below before committing to the full 500. Requires: pip install antspyx nibabel numpy """ import os import glob import numpy as np import ants import nibabel as nib # ---- EDIT THESE FOR YOUR MACHINE ---- RAW_ROOT = r"D:\jainam\UCSF-PDGM-v5" # where datadownload.py put the raw files OUT_ROOT = r"D:\jainam\UCSF-PDGM-v5-preprocessed" # where final preprocessed volumes go ATLAS_PATH = r"D:\jainam\CMTLNet\CMTLNet\preprocessing\regdata\spgr_unstrip_lps_b.nii.gz" TARGET_SHAPE = (160, 192, 160) LIMIT = None # set to None to run all subjects; test with a small number first! # -------------------------------------- def get_bbox_from_mask(mask, outside_value=0): coords = np.where(mask != outside_value) return ( [int(coords[0].min()), int(coords[0].max()) + 1], [int(coords[1].min()), int(coords[1].max()) + 1], [int(coords[2].min()), int(coords[2].max()) + 1], ) def crop_to_bbox(image, bbox): resizer = tuple(slice(b[0], b[1]) for b in bbox) return image[resizer] def pad_to_shape(arr, target_shape): """Pad with zeros to target_shape (assumes arr is <= target on every axis after the bbox crop; if not, center-crop the overflow first).""" out = np.zeros(target_shape, dtype=arr.dtype) src_slices, dst_slices = [], [] for s, t in zip(arr.shape, target_shape): if s <= t: pad_start = (t - s) // 2 src_slices.append(slice(0, s)) dst_slices.append(slice(pad_start, pad_start + s)) else: start = (s - t) // 2 src_slices.append(slice(start, start + t)) dst_slices.append(slice(0, t)) out[tuple(dst_slices)] = arr[tuple(src_slices)] return out def register_subject(sid: str, atlas): raw_folder = os.path.join(RAW_ROOT, f"{sid}_nifti") t1c_path = os.path.join(raw_folder, f"{sid}_T1c.nii.gz") t2_path = os.path.join(raw_folder, f"{sid}_T2.nii.gz") flair_path = os.path.join(raw_folder, f"{sid}_FLAIR.nii.gz") mask_path = os.path.join(raw_folder, f"{sid}_tumor_segmentation.nii.gz") if not all(os.path.exists(p) for p in [t1c_path, t2_path, flair_path, mask_path]): print(f" [skip] {sid}: missing one or more raw files") return # 1. T1c -> atlas t1c = ants.image_read(t1c_path) reg_t1c = ants.registration(fixed=atlas, moving=t1c, type_of_transform="Affine") t1c_warped = reg_t1c["warpedmovout"] # 2. T2 -> registered T1c t2 = ants.image_read(t2_path) reg_t2 = ants.registration(fixed=t1c_warped, moving=t2, type_of_transform="Affine") t2_warped = reg_t2["warpedmovout"] # 3. FLAIR -> registered T1c flair = ants.image_read(flair_path) reg_flair = ants.registration(fixed=t1c_warped, moving=flair, type_of_transform="Affine") flair_warped = reg_flair["warpedmovout"] # 4. mask rides on T1c's transform, nearest-neighbor (no independent registration) mask = ants.image_read(mask_path) mask_warped = ants.apply_transforms( fixed=atlas, moving=mask, transformlist=reg_t1c["fwdtransforms"], interpolator="nearestNeighbor", ) # convert to numpy for crop/pad t1c_np = t1c_warped.numpy() t2_np = t2_warped.numpy() flair_np = flair_warped.numpy() mask_np = mask_warped.numpy() combined = t1c_np + t2_np + flair_np bbox = get_bbox_from_mask(combined) t1c_c = pad_to_shape(crop_to_bbox(t1c_np, bbox), TARGET_SHAPE) t2_c = pad_to_shape(crop_to_bbox(t2_np, bbox), TARGET_SHAPE) flair_c = pad_to_shape(crop_to_bbox(flair_np, bbox), TARGET_SHAPE) mask_c = pad_to_shape(crop_to_bbox(mask_np, bbox), TARGET_SHAPE) mask_c = (mask_c > 0).astype(np.uint8) out_folder = os.path.join(OUT_ROOT, sid) os.makedirs(out_folder, exist_ok=True) affine = np.eye(4) # spatial correspondence no longer meaningful post-crop/pad; identity is fine for a CNN pipeline nib.Nifti1Image(t1c_c.astype(np.float32), affine).to_filename(os.path.join(out_folder, "T1C.nii.gz")) nib.Nifti1Image(t2_c.astype(np.float32), affine).to_filename(os.path.join(out_folder, "T2.nii.gz")) nib.Nifti1Image(flair_c.astype(np.float32), affine).to_filename(os.path.join(out_folder, "FLAIR.nii.gz")) nib.Nifti1Image(mask_c, affine).to_filename(os.path.join(out_folder, "mask.nii.gz")) print(f" [done] {sid} final shape={t1c_c.shape}") if __name__ == "__main__": import warnings warnings.filterwarnings("ignore") atlas = ants.image_read(ATLAS_PATH) subject_folders = sorted(glob.glob(os.path.join(RAW_ROOT, "UCSF-PDGM-*_nifti"))) sids = [os.path.basename(f).replace("_nifti", "") for f in subject_folders] if LIMIT is not None: sids = sids[:LIMIT] print(f"Processing {len(sids)} subjects...") for i, sid in enumerate(sids): print(f"[{i+1}/{len(sids)}] {sid}") try: register_subject(sid, atlas) except Exception as e: print(f" [ERROR] {sid}: {e}")