Resampling to a uniform spacing with SimpleITK

MediumMedical image analysisMedical imaging

Goal: Harmonising voxel size (spacing) between scans from different machines.

Python — example.py
import SimpleITK as sitk

img = sitk.Image(128, 128, 40, sitk.sitkFloat32)
img.SetSpacing((0.8, 0.8, 3.0))
img.SetOrigin((-50.0, -50.0, 0.0))

new_spacing = (1.0, 1.0, 1.0)
new_size = [round(sz * sp / ns) for sz, sp, ns in zip(img.GetSize(), img.GetSpacing(), new_spacing)]
res = sitk.Resample(img, new_size, sitk.Transform(), sitk.sitkLinear, img.GetOrigin(),
                    new_spacing, img.GetDirection(), 0.0, img.GetPixelID())
print("Size and spacing before:", img.GetSize(), img.GetSpacing())
print("Size and spacing after:", res.GetSize(), res.GetSpacing())
print("Origin preserved:", res.GetOrigin())

Code explanation

Medical images have a physical spacing in millimetres. We resample to 1×1×1 mm, computing the new size from the ratio, and use linear interpolation for the image (for masks use nearest neighbour). Spatial information (origin and direction) is preserved.

Requirements

Shell
pip install SimpleITK

How to run

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

Shell
python example.py

Output recorded during testing

Size and spacing before: (128, 128, 40) (0.8, 0.8, 3.0)
Size and spacing after: (102, 102, 120) (1.0, 1.0, 1.0)
Origin preserved: (-50.0, -50.0, 0.0)

This example was actually run and tested on 21 November 2026 on a CPU — SimpleITK 2.5.8, 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