Sliding-window inference on a large volume

AdvancedImage segmentationMedical segmentation

Goal: Running a network on a volume larger than the training size without running out of memory.

Python — example.py
import torch
from monai.inferers import sliding_window_inference
from monai.networks.nets import UNet

net = UNet(3, 1, 2, channels=(8, 16, 32), strides=(2, 2)).eval()
volume = torch.randn(1, 1, 160, 160, 96)
with torch.no_grad():
    out = sliding_window_inference(volume, roi_size=(64, 64, 64), sw_batch_size=4,
                                   predictor=net, overlap=0.25, mode="gaussian")
print("Input size:", tuple(volume.shape))
print("Output size:", tuple(out.shape))

Code explanation

sliding_window_inference splits the volume into patches of roi_size with a given overlap, runs the network on each batch of patches, then merges the results with weights. This is how a network trained on 64³ patches is applied to a full scan.

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

Input size: (1, 1, 160, 160, 96)
Output size: (1, 2, 160, 160, 96)

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