MRI augmentation and patch sampling with TorchIO

MediumMedical image analysisMedical imaging

Goal: Applying realistic distortions and extracting patches for training.

Python — example.py
import torch, torchio as tio

torch.manual_seed(0)
subject = tio.Subject(mri=tio.ScalarImage(tensor=torch.rand(1, 64, 64, 48)),
                      seg=tio.LabelMap(tensor=(torch.rand(1, 64, 64, 48) > 0.9).int()))
tf = tio.Compose([tio.RescaleIntensity(out_min_max=(0, 1)), tio.RandomAffine(degrees=10),
                  tio.RandomBiasField(), tio.RandomNoise(std=0.02)])
aug = tf(subject)
print("Applied transforms:", [t.name for t in aug.history])
sampler = tio.data.UniformSampler(patch_size=32)
patches = list(sampler(aug, num_patches=3))
print("Number of patches:", len(patches), "| patch shape:", tuple(patches[0]["mri"].data.shape))

Code explanation

A Subject groups the image and the mask, and spatial transforms are applied to both together. RandomBiasField simulates magnetic field inhomogeneity in MRI. Then UniformSampler draws fixed-size patches for training with limited memory.

Requirements

Shell
pip install torchio torch

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

Applied transforms: ['RescaleIntensity', 'Affine', 'BiasField', 'Noise']
Number of patches: 3 | patch shape: (1, 32, 32, 32)

This example was actually run and tested on 21 November 2026 on a CPU — torchio 1.2.1, torch 2.15.0, python 3.13.18

Libraries used

Related examples

AdvancedITKRun and tested

A gradient magnitude filter in ITK

Applying an ITK filter to a 3D image through its functional Python API.

Medical image analysis · Medical imaging