File size: 9,261 Bytes
b9b7fea | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | #!/usr/bin/env python3
"""
Combined M&Ms-2 preprocessing script (mirrors prepare_acdc.py):
1. Read per-patient folders from raw_dataset/MnMs2_original/{train,val,test}/
2. Copy SAX ED/ES (image + GT) into standardised lvsa_SR_ED/ES naming
3. Sabotage slices with random in-plane shifts
4. Generate JSON index for QC software
Notes:
- Only SAX is processed. LAX files are 2D single-slice and don't fit the
multi-slice shift semantic used by the QC pipeline.
- Output patient folders are named mnms2_{split}_{id} to avoid ID collisions
across train/val/test and with the ACDC sabotaged_dataset/.
- M&Ms-2 segmentation labels are 1=LV, 2=MYO, 3=RV (ACDC uses 1=RV, 2=MYO,
3=LV). No remapping is applied — consumers should be aware per dataset.
"""
import json
import shutil
import argparse
import random
from pathlib import Path
import numpy as np
import nibabel as nib
def find_patient_dirs(source_dir: Path):
"""Find all patient directories across train/, val/, test/ splits.
Returns list of (split, patient_dir) tuples.
"""
patient_dirs = []
for split in ["train", "val", "test"]:
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.isdigit():
patient_dirs.append((split, 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 SAX files to lvsa_SR naming,
sabotage slices with random shifts, and generate JSON index.
Args:
source_dir: MnMs2_original directory containing train/ val/ test/
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_entries = find_patient_dirs(source_path)
if not patient_entries:
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_entries)} patients across train/val/test")
json_index = {}
for split, patient_dir in patient_entries:
pid = patient_dir.name # e.g. "001"
out_name = f"mnms2_{split}_{pid}"
rename_map = {
f"{pid}_sax_ed.nii.gz": "lvsa_SR_ED.nii.gz",
f"{pid}_sax_ed_gt.nii.gz": "seg_lvsa_SR_ED.nii.gz",
f"{pid}_sax_es.nii.gz": "lvsa_SR_ES.nii.gz",
f"{pid}_sax_es_gt.nii.gz": "seg_lvsa_SR_ES.nii.gz",
}
missing = [src for src in rename_map if not (patient_dir / src).exists()]
if missing:
print(f"\n Warning: {split}/{pid} missing {missing}, skipping")
continue
print(f"\n{out_name}:")
patient_out = output_path / out_name
if not dry_run:
patient_out.mkdir(parents=True, exist_ok=True)
for src_name, new_name in rename_map.items():
src = patient_dir / src_name
dst = patient_out / new_name
if dry_run:
print(f" {src_name} -> {out_name}/{new_name}")
else:
shutil.copy2(src, dst)
print(f" Copied: {src_name} -> {out_name}/{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']}")
json_index[str(patient_out.resolve())] = patient_sabotage
json_name = (f"mnms2_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 M&Ms-2 SAX dataset: rename files, sabotage, and generate JSON index')
parser.add_argument('--source', type=str,
default='raw_dataset/MnMs2_original',
help='MnMs2_original directory containing train/ val/ test/')
parser.add_argument('--output', type=str,
default='sabotaged_dataset/sabotaged_mnms2',
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()
|