Reading and Writing for Images and Transforms


There are numerous file formats support by SimpleITK’s image readers and writers. Support for a particular format is handled by a specific ITK ImageIO class. By default, the ImageIO is automatically determined for a particular file based on the file name suffix and/or the contents of the file’s header. Advanced SimpleITK installations can configure or extend which file formats are supported by SimpleITK. A list of registered ImageIO’s can be found using the GetRegisteredImageIOs() method, but is posted here:

A read and write example using SimpleITK’s ImageFileReader and ImageFileWriter classes:

import SimpleITK as sitk

reader = sitk.ImageFileReader()
image = reader.Execute();

writer = sitk.ImageFileWriter()

The above example specifies using the BMPImageIO to read the file. If that line is omitted, SimpleITK would determine which IO to use automatically, based on the file name’s suffix and/or the file’s header.

A more compact example using SimpleITK’s procedural interface:

import SimpleITK as sitk

image = sitk.ReadImage(inputImagefileName, imageIO="BMPImageIO")
sitk.WriteImage(image, outputImagefileName)


In SimpleITK, transformation files can be written in several different formats. Just like there are numerous IOs for images, there are several for transforms, including TxtTransformIO, MINCTransformIO, HDF5TransformIO, and MatlabTransformIO (although this list can be extended as well). These support a variety of file formats, including .txt, .tfm, .xfm, .hdf and .mat.

Because of their size, displacement fields may require more careful attention. To save a displacement field we recommend using one of the binary transformation file formats (e.g. .hdf, .mat). Saving it in a text based format results in significantly larger files and longer IO runtimes. Another option is to save the displacement field found in a DisplacementFieldTransform object as an image (.nrrd, .nhdr, .mha, .mhd, .nii, .nii.gz).

Take for example of a transformation written to and read from a file in Python:

basic_transform = sitk.Euler2DTransform()

sitk.WriteTransform(basic_transform, 'euler2D.tfm')
read_result = sitk.ReadTransform('euler2D.tfm')

assert(str(type(read_result) != type(basic_transform)))

read_result will be an object of the generic sitk.Transform() class and basic_transform will be of sitk.Euler2DTransform(), but both represent the same transformation. Although this example only uses a single SimpleITK transformation, a .tfm file can hold a composite (set of transformations).