A MONAI transform pipeline for a 3D volume

BeginnerMedical image analysisMedical imaging

Goal: Normalising the intensity of an MRI volume, cropping it and adding random augmentation.

Python — example.py
import numpy as np, torch
from monai.transforms import Compose, NormalizeIntensity, CropForeground, RandFlip, ToTensor
from monai.utils import set_determinism

set_determinism(seed=0)
vol = np.zeros((1, 64, 64, 48), dtype=np.float32)
vol[:, 16:48, 20:44, 10:38] = np.random.default_rng(0).normal(100, 20, (32, 24, 28))
tf = Compose([NormalizeIntensity(nonzero=True), CropForeground(), RandFlip(prob=1.0, spatial_axis=0), ToTensor()])
out = tf(vol)
print("Shape before:", vol.shape, "after cropping:", tuple(out.shape))
nz = out[out != 0]
print(f"Mean intensity after normalisation: {nz.mean().item():.3f}, std: {nz.std().item():.3f}")

Code explanation

MONAI transforms work on arrays in (channel, depth, height, width) format. We apply intensity normalisation, then foreground cropping, then a random flip. Here the volume is randomly generated; with real NIfTI files add LoadImaged at the start.

Requirements

Shell
pip install monai torch

How to run

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

Shell
python example.py

Output recorded during testing

Shape before: (1, 64, 64, 48) after cropping: (1, 32, 24, 28)
Mean intensity after normalisation: -0.000, std: 1.000

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

Libraries used

Related examples

MediumMONAIRun and tested

A 3D UNet with Dice loss in MONAI

Training a small segmentation network for a few steps on synthetic data and monitoring the Dice metric.

Image segmentation · Medical segmentation