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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Combined M&Ms-2 preprocessing script (mirrors prepare_acdc.py):
|
| 4 |
+
1. Read per-patient folders from raw_dataset/MnMs2_original/{train,val,test}/
|
| 5 |
+
2. Copy SAX ED/ES (image + GT) into standardised lvsa_SR_ED/ES naming
|
| 6 |
+
3. Sabotage slices with random in-plane shifts
|
| 7 |
+
4. Generate JSON index for QC software
|
| 8 |
+
|
| 9 |
+
Notes:
|
| 10 |
+
- Only SAX is processed. LAX files are 2D single-slice and don't fit the
|
| 11 |
+
multi-slice shift semantic used by the QC pipeline.
|
| 12 |
+
- Output patient folders are named mnms2_{split}_{id} to avoid ID collisions
|
| 13 |
+
across train/val/test and with the ACDC sabotaged_dataset/.
|
| 14 |
+
- M&Ms-2 segmentation labels are 1=LV, 2=MYO, 3=RV (ACDC uses 1=RV, 2=MYO,
|
| 15 |
+
3=LV). No remapping is applied — consumers should be aware per dataset.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import json
|
| 19 |
+
import shutil
|
| 20 |
+
import argparse
|
| 21 |
+
import random
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
import nibabel as nib
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def find_patient_dirs(source_dir: Path):
|
| 29 |
+
"""Find all patient directories across train/, val/, test/ splits.
|
| 30 |
+
|
| 31 |
+
Returns list of (split, patient_dir) tuples.
|
| 32 |
+
"""
|
| 33 |
+
patient_dirs = []
|
| 34 |
+
for split in ["train", "val", "test"]:
|
| 35 |
+
split_dir = source_dir / split
|
| 36 |
+
if not split_dir.exists():
|
| 37 |
+
continue
|
| 38 |
+
for d in sorted(split_dir.iterdir()):
|
| 39 |
+
if d.is_dir() and d.name.isdigit():
|
| 40 |
+
patient_dirs.append((split, d))
|
| 41 |
+
return patient_dirs
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def sabotage_slices(img_path: Path, seg_path: Path | None,
|
| 45 |
+
sabotage_ratio: float, max_shift: int,
|
| 46 |
+
dry_run: bool = True) -> list[dict]:
|
| 47 |
+
"""
|
| 48 |
+
Randomly shift slices in-plane to simulate respiratory motion misalignment.
|
| 49 |
+
|
| 50 |
+
For each slice (along the z-axis), with probability sabotage_ratio, apply a
|
| 51 |
+
random x/y pixel shift to both the image and its paired segmentation.
|
| 52 |
+
|
| 53 |
+
Returns a list of dicts describing which slices were shifted and by how much.
|
| 54 |
+
"""
|
| 55 |
+
img_nii = nib.load(img_path)
|
| 56 |
+
img_data = img_nii.get_fdata()
|
| 57 |
+
n_slices = img_data.shape[2]
|
| 58 |
+
|
| 59 |
+
seg_nii = None
|
| 60 |
+
seg_data = None
|
| 61 |
+
if seg_path and seg_path.exists():
|
| 62 |
+
seg_nii = nib.load(seg_path)
|
| 63 |
+
seg_data = seg_nii.get_fdata()
|
| 64 |
+
|
| 65 |
+
shifts = []
|
| 66 |
+
for z in range(n_slices):
|
| 67 |
+
if random.random() >= sabotage_ratio:
|
| 68 |
+
continue
|
| 69 |
+
dx = random.randint(-max_shift, max_shift)
|
| 70 |
+
dy = random.randint(-max_shift, max_shift)
|
| 71 |
+
if dx == 0 and dy == 0:
|
| 72 |
+
continue
|
| 73 |
+
|
| 74 |
+
shifts.append({"slice": z, "dx": dx, "dy": dy})
|
| 75 |
+
|
| 76 |
+
if not dry_run:
|
| 77 |
+
img_data[:, :, z] = np.roll(img_data[:, :, z], shift=dx, axis=0)
|
| 78 |
+
img_data[:, :, z] = np.roll(img_data[:, :, z], shift=dy, axis=1)
|
| 79 |
+
if seg_data is not None:
|
| 80 |
+
seg_data[:, :, z] = np.roll(seg_data[:, :, z], shift=dx, axis=0)
|
| 81 |
+
seg_data[:, :, z] = np.roll(seg_data[:, :, z], shift=dy, axis=1)
|
| 82 |
+
|
| 83 |
+
if not dry_run and shifts:
|
| 84 |
+
# Cast back to original dtype so nibabel doesn't auto-rescale float64
|
| 85 |
+
# into the target integer range (which would corrupt stored labels).
|
| 86 |
+
img_out = img_data.astype(img_nii.get_data_dtype())
|
| 87 |
+
nib.save(nib.Nifti1Image(img_out, img_nii.affine, img_nii.header), img_path)
|
| 88 |
+
if seg_nii is not None and seg_data is not None:
|
| 89 |
+
seg_out = seg_data.astype(seg_nii.get_data_dtype())
|
| 90 |
+
nib.save(nib.Nifti1Image(seg_out, seg_nii.affine, seg_nii.header), seg_path)
|
| 91 |
+
|
| 92 |
+
return shifts
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def process_patients(source_dir: str, output_dir: str, dry_run: bool = True,
|
| 96 |
+
sabotage_ratio: float = 0.5, max_shift: int = 5,
|
| 97 |
+
seed: int = 42):
|
| 98 |
+
"""
|
| 99 |
+
Read per-patient directories, rename SAX files to lvsa_SR naming,
|
| 100 |
+
sabotage slices with random shifts, and generate JSON index.
|
| 101 |
+
|
| 102 |
+
Args:
|
| 103 |
+
source_dir: MnMs2_original directory containing train/ val/ test/
|
| 104 |
+
output_dir: Directory where per-patient folders will be created
|
| 105 |
+
dry_run: If True, only show what would be done
|
| 106 |
+
sabotage_ratio: Probability of shifting each slice (0.0 to 1.0)
|
| 107 |
+
max_shift: Maximum pixel shift in each direction
|
| 108 |
+
"""
|
| 109 |
+
source_path = Path(source_dir)
|
| 110 |
+
param_subdir = f"seed{seed}_ratio{sabotage_ratio}_shift{max_shift}"
|
| 111 |
+
output_path = Path(output_dir) / param_subdir
|
| 112 |
+
|
| 113 |
+
patient_entries = find_patient_dirs(source_path)
|
| 114 |
+
if not patient_entries:
|
| 115 |
+
print(f"Error: No patient directories found in {source_path}")
|
| 116 |
+
return
|
| 117 |
+
|
| 118 |
+
print(f"\n{'DRY RUN MODE' if dry_run else 'EXECUTING'}")
|
| 119 |
+
print("=" * 50)
|
| 120 |
+
print(f"Found {len(patient_entries)} patients across train/val/test")
|
| 121 |
+
|
| 122 |
+
json_index = {}
|
| 123 |
+
|
| 124 |
+
for split, patient_dir in patient_entries:
|
| 125 |
+
pid = patient_dir.name # e.g. "001"
|
| 126 |
+
out_name = f"mnms2_{split}_{pid}"
|
| 127 |
+
|
| 128 |
+
rename_map = {
|
| 129 |
+
f"{pid}_sax_ed.nii.gz": "lvsa_SR_ED.nii.gz",
|
| 130 |
+
f"{pid}_sax_ed_gt.nii.gz": "seg_lvsa_SR_ED.nii.gz",
|
| 131 |
+
f"{pid}_sax_es.nii.gz": "lvsa_SR_ES.nii.gz",
|
| 132 |
+
f"{pid}_sax_es_gt.nii.gz": "seg_lvsa_SR_ES.nii.gz",
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
missing = [src for src in rename_map if not (patient_dir / src).exists()]
|
| 136 |
+
if missing:
|
| 137 |
+
print(f"\n Warning: {split}/{pid} missing {missing}, skipping")
|
| 138 |
+
continue
|
| 139 |
+
|
| 140 |
+
print(f"\n{out_name}:")
|
| 141 |
+
|
| 142 |
+
patient_out = output_path / out_name
|
| 143 |
+
if not dry_run:
|
| 144 |
+
patient_out.mkdir(parents=True, exist_ok=True)
|
| 145 |
+
|
| 146 |
+
for src_name, new_name in rename_map.items():
|
| 147 |
+
src = patient_dir / src_name
|
| 148 |
+
dst = patient_out / new_name
|
| 149 |
+
if dry_run:
|
| 150 |
+
print(f" {src_name} -> {out_name}/{new_name}")
|
| 151 |
+
else:
|
| 152 |
+
shutil.copy2(src, dst)
|
| 153 |
+
print(f" Copied: {src_name} -> {out_name}/{new_name}")
|
| 154 |
+
|
| 155 |
+
# Sabotage: randomly shift slices to simulate respiratory misalignment
|
| 156 |
+
patient_sabotage = {}
|
| 157 |
+
if sabotage_ratio > 0:
|
| 158 |
+
for phase in ["ED", "ES"]:
|
| 159 |
+
img_file = patient_out / f"lvsa_SR_{phase}.nii.gz"
|
| 160 |
+
seg_file = patient_out / f"seg_lvsa_SR_{phase}.nii.gz"
|
| 161 |
+
if dry_run:
|
| 162 |
+
print(f" Would sabotage lvsa_SR_{phase} "
|
| 163 |
+
f"(ratio={sabotage_ratio}, max_shift={max_shift}px)")
|
| 164 |
+
else:
|
| 165 |
+
if img_file.exists():
|
| 166 |
+
shifts = sabotage_slices(
|
| 167 |
+
img_file, seg_file,
|
| 168 |
+
sabotage_ratio, max_shift, dry_run=False)
|
| 169 |
+
patient_sabotage[phase] = {
|
| 170 |
+
"sabotaged": len(shifts) > 0,
|
| 171 |
+
"shifts": shifts,
|
| 172 |
+
}
|
| 173 |
+
if shifts:
|
| 174 |
+
print(f" Sabotaged lvsa_SR_{phase}: "
|
| 175 |
+
f"shifted {len(shifts)}/{nib.load(img_file).shape[2]} slices")
|
| 176 |
+
for s in shifts:
|
| 177 |
+
print(f" slice {s['slice']}: dx={s['dx']}, dy={s['dy']}")
|
| 178 |
+
|
| 179 |
+
json_index[str(patient_out.resolve())] = patient_sabotage
|
| 180 |
+
|
| 181 |
+
json_name = (f"mnms2_qc_dataset"
|
| 182 |
+
f"_seed{seed}"
|
| 183 |
+
f"_ratio{sabotage_ratio}"
|
| 184 |
+
f"_shift{max_shift}.json")
|
| 185 |
+
json_path = output_path / json_name
|
| 186 |
+
if dry_run:
|
| 187 |
+
print(f"\nWould write JSON index ({len(json_index)} patients) to {json_path}")
|
| 188 |
+
else:
|
| 189 |
+
with open(json_path, 'w') as f:
|
| 190 |
+
json.dump(json_index, f, indent=4, sort_keys=True)
|
| 191 |
+
print(f"\nWrote JSON index ({len(json_index)} patients) to {json_path}")
|
| 192 |
+
|
| 193 |
+
print("\n" + "=" * 50)
|
| 194 |
+
if dry_run:
|
| 195 |
+
print("DRY RUN COMPLETE - no files were copied")
|
| 196 |
+
print("Run with --execute to perform the operation")
|
| 197 |
+
else:
|
| 198 |
+
print(f"COMPLETE - output at {output_path}")
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def main():
|
| 202 |
+
parser = argparse.ArgumentParser(description='Preprocess M&Ms-2 SAX dataset: rename files, sabotage, and generate JSON index')
|
| 203 |
+
parser.add_argument('--source', type=str,
|
| 204 |
+
default='raw_dataset/MnMs2_original',
|
| 205 |
+
help='MnMs2_original directory containing train/ val/ test/')
|
| 206 |
+
parser.add_argument('--output', type=str,
|
| 207 |
+
default='sabotaged_dataset/sabotaged_mnms2',
|
| 208 |
+
help='Parent output directory; a seed{N}_ratio{R}_shift{S} '
|
| 209 |
+
'subfolder is auto-created inside it')
|
| 210 |
+
parser.add_argument('--execute', action='store_true',
|
| 211 |
+
help='Actually perform the copy and rename (default is dry run)')
|
| 212 |
+
parser.add_argument('--sabotage-ratio', type=float, default=0.5,
|
| 213 |
+
help='Probability of shifting each slice (0.0-1.0, default: 0.5)')
|
| 214 |
+
parser.add_argument('--max-shift', type=int, default=5,
|
| 215 |
+
help='Maximum pixel shift per direction (default: 5)')
|
| 216 |
+
parser.add_argument('--seed', type=int, default=42,
|
| 217 |
+
help='Random seed for reproducibility (default: 42)')
|
| 218 |
+
|
| 219 |
+
args = parser.parse_args()
|
| 220 |
+
random.seed(args.seed)
|
| 221 |
+
np.random.seed(args.seed)
|
| 222 |
+
process_patients(args.source, args.output, dry_run=not args.execute,
|
| 223 |
+
sabotage_ratio=args.sabotage_ratio, max_shift=args.max_shift,
|
| 224 |
+
seed=args.seed)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
if __name__ == "__main__":
|
| 228 |
+
main()
|