#!/usr/bin/env python3 """ Combined ACDC preprocessing script: 1. Read per-patient folders from the original ACDC dataset 2. Rename and copy files into standardised lvsa_SR_ED/ES naming 3. Generate JSON index for QC software """ import re import json import shutil import argparse import random from pathlib import Path from collections import defaultdict import numpy as np import nibabel as nib def find_patient_dirs(source_dir: Path): """Find all patient directories across training/ and testing/ splits.""" patient_dirs = [] for split in ["training", "testing"]: split_dir = source_dir / split if not split_dir.exists(): continue for d in sorted(split_dir.iterdir()): if d.is_dir() and d.name.startswith("patient"): patient_dirs.append(d) return patient_dirs def sabotage_slices(img_path: Path, seg_path: Path | None, sabotage_ratio: float, max_shift: int, dry_run: bool = True) -> list[dict]: """ Randomly shift slices in-plane to simulate respiratory motion misalignment. For each slice (along the z-axis), with probability sabotage_ratio, apply a random x/y pixel shift to both the image and its paired segmentation. Returns a list of dicts describing which slices were shifted and by how much. """ img_nii = nib.load(img_path) img_data = img_nii.get_fdata() n_slices = img_data.shape[2] seg_nii = None seg_data = None if seg_path and seg_path.exists(): seg_nii = nib.load(seg_path) seg_data = seg_nii.get_fdata() shifts = [] for z in range(n_slices): if random.random() >= sabotage_ratio: continue dx = random.randint(-max_shift, max_shift) dy = random.randint(-max_shift, max_shift) if dx == 0 and dy == 0: continue shifts.append({"slice": z, "dx": dx, "dy": dy}) if not dry_run: img_data[:, :, z] = np.roll(img_data[:, :, z], shift=dx, axis=0) img_data[:, :, z] = np.roll(img_data[:, :, z], shift=dy, axis=1) if seg_data is not None: seg_data[:, :, z] = np.roll(seg_data[:, :, z], shift=dx, axis=0) seg_data[:, :, z] = np.roll(seg_data[:, :, z], shift=dy, axis=1) if not dry_run and shifts: # Cast back to original dtype so nibabel doesn't auto-rescale float64 # into the target integer range (which would corrupt stored labels). img_out = img_data.astype(img_nii.get_data_dtype()) nib.save(nib.Nifti1Image(img_out, img_nii.affine, img_nii.header), img_path) if seg_nii is not None and seg_data is not None: seg_out = seg_data.astype(seg_nii.get_data_dtype()) nib.save(nib.Nifti1Image(seg_out, seg_nii.affine, seg_nii.header), seg_path) return shifts def process_patients(source_dir: str, output_dir: str, dry_run: bool = True, sabotage_ratio: float = 0.5, max_shift: int = 5, seed: int = 42): """ Read per-patient directories, rename files to lvsa_SR naming, sabotage slices with random shifts, and generate JSON index. Args: source_dir: ACDC_original directory containing training/ and testing/ output_dir: Directory where per-patient folders will be created dry_run: If True, only show what would be done sabotage_ratio: Probability of shifting each slice (0.0 to 1.0) max_shift: Maximum pixel shift in each direction """ source_path = Path(source_dir) param_subdir = f"seed{seed}_ratio{sabotage_ratio}_shift{max_shift}" output_path = Path(output_dir) / param_subdir patient_dirs = find_patient_dirs(source_path) if not patient_dirs: print(f"Error: No patient directories found in {source_path}") return print(f"\n{'DRY RUN MODE' if dry_run else 'EXECUTING'}") print("=" * 50) print(f"Found {len(patient_dirs)} patients") json_index = {} for patient_dir in patient_dirs: pid = patient_dir.name # Find frame files: image and ground-truth pairs frames = defaultdict(dict) for f in sorted(patient_dir.glob(f"{pid}_frame*.nii.gz")): gt_match = re.match(rf'{pid}_frame(\d+)_gt\.nii\.gz', f.name) img_match = re.match(rf'{pid}_frame(\d+)\.nii\.gz', f.name) if gt_match: frames[int(gt_match.group(1))]['gt'] = f elif img_match: frames[int(img_match.group(1))]['img'] = f frame_numbers = sorted(frames.keys()) if len(frame_numbers) < 2: print(f"\n Warning: {pid} has only {len(frame_numbers)} frame(s), skipping") continue ed_frame = frame_numbers[0] es_frame = frame_numbers[-1] print(f"\n{pid}: ED=frame{ed_frame:02d} ES=frame{es_frame:02d}") patient_out = output_path / pid if not dry_run: patient_out.mkdir(parents=True, exist_ok=True) rename_map = { (ed_frame, 'img'): 'lvsa_SR_ED.nii.gz', (ed_frame, 'gt'): 'seg_lvsa_SR_ED.nii.gz', (es_frame, 'img'): 'lvsa_SR_ES.nii.gz', (es_frame, 'gt'): 'seg_lvsa_SR_ES.nii.gz', } for (fnum, ftype), new_name in rename_map.items(): if ftype in frames.get(fnum, {}): src = frames[fnum][ftype] dst = patient_out / new_name if dry_run: print(f" {src.name} -> {pid}/{new_name}") else: shutil.copy2(src, dst) print(f" Copied: {src.name} -> {pid}/{new_name}") # Sabotage: randomly shift slices to simulate respiratory misalignment patient_sabotage = {} if sabotage_ratio > 0: for phase in ["ED", "ES"]: img_file = patient_out / f"lvsa_SR_{phase}.nii.gz" seg_file = patient_out / f"seg_lvsa_SR_{phase}.nii.gz" if dry_run: print(f" Would sabotage lvsa_SR_{phase} " f"(ratio={sabotage_ratio}, max_shift={max_shift}px)") else: if img_file.exists(): shifts = sabotage_slices( img_file, seg_file, sabotage_ratio, max_shift, dry_run=False) patient_sabotage[phase] = { "sabotaged": len(shifts) > 0, "shifts": shifts, } if shifts: print(f" Sabotaged lvsa_SR_{phase}: " f"shifted {len(shifts)}/{nib.load(img_file).shape[2]} slices") for s in shifts: print(f" slice {s['slice']}: dx={s['dx']}, dy={s['dy']}") # Add to JSON index (absolute path as key) json_index[str(patient_out.resolve())] = patient_sabotage # Write JSON index — encode key parameters in filename json_name = (f"acdc_qc_dataset" f"_seed{seed}" f"_ratio{sabotage_ratio}" f"_shift{max_shift}.json") json_path = output_path / json_name if dry_run: print(f"\nWould write JSON index ({len(json_index)} patients) to {json_path}") else: with open(json_path, 'w') as f: json.dump(json_index, f, indent=4, sort_keys=True) print(f"\nWrote JSON index ({len(json_index)} patients) to {json_path}") print("\n" + "=" * 50) if dry_run: print("DRY RUN COMPLETE - no files were copied") print("Run with --execute to perform the operation") else: print(f"COMPLETE - output at {output_path}") def main(): parser = argparse.ArgumentParser(description='Preprocess ACDC dataset: rename files and generate JSON index') parser.add_argument('--source', type=str, default='raw_dataset/ACDC_original', help='ACDC_original directory containing training/ and testing/') parser.add_argument('--output', type=str, default='sabotaged_dataset/sabotaged_acdc', help='Parent output directory; a seed{N}_ratio{R}_shift{S} ' 'subfolder is auto-created inside it') parser.add_argument('--execute', action='store_true', help='Actually perform the copy and rename (default is dry run)') parser.add_argument('--sabotage-ratio', type=float, default=0.5, help='Probability of shifting each slice (0.0-1.0, default: 0.5)') parser.add_argument('--max-shift', type=int, default=5, help='Maximum pixel shift per direction (default: 5)') parser.add_argument('--seed', type=int, default=42, help='Random seed for reproducibility (default: 42)') args = parser.parse_args() random.seed(args.seed) np.random.seed(args.seed) process_patients(args.source, args.output, dry_run=not args.execute, sabotage_ratio=args.sabotage_ratio, max_shift=args.max_shift, seed=args.seed) if __name__ == "__main__": main()