Image, mesh, and transform I/O
ITK moves images, meshes, spatial-object scenes, and transforms between memory and files through shared reader and writer roles. Format services apply the rules of each file type, while factories choose a service for each read or write request. Image geometry and supported metadata travel with image data so that import and export preserve both values and physical space.
I/O system model
Shared I/O boundary
The I/O system separates a data flow from the rules of a file format. Image, mesh, and transform base interfaces define stable boundaries where a service checks a path and exchanges data with the matching reader or writer. Spatial-object readers and writers use the same idea through scene converters.
The data families have different payloads:
| Data family | In-memory result | File-facing responsibility |
|---|---|---|
| Image | Typed samples plus grid geometry | Dimensions, pixel type, spacing, origin, direction, regions, and format metadata |
| Mesh | Points, cells, and optional point or cell data | Geometry, topology, data arrays, and file encoding |
| Spatial object | A scene object or object hierarchy | Object type, hierarchy, transforms, properties, and supported scene data |
| Transform | One transform or a transform list | Transform type, parameters, fixed parameters, and precision |
Format support stays outside these shared roles. This lets an application change the file format without changing the image, mesh, or transform pipeline. See format integration and I/O factories for the format-module contract.
References: Modules/…/itkImageIOBase.h• L50-67 Modules/…/itkMeshIOBase.h• L46-69 Modules/…/itkTransformIOBase.h• L43-55 Modules/…/itkSpatialObjectReader.h• L29-36
Factory selection
A family factory turns a path and an I/O mode into a format service. It checks registered services with either a read or write probe. The first service that accepts the path becomes the service used by the higher-level reader or writer.
Image selection gives advertised suffixes an early check and then probes remaining services. Mesh and transform selection probe their registered services in order. A caller can set a service directly when a path has no useful suffix or when the caller must force a format choice.
This diagram shows the common selection path and the point where a direct service can replace automatic choice.
flowchart LR
A[Reader or writer] --> B{I/O service supplied?}
B -->|Yes| E[Selected format service]
B -->|No| C[Family factory]
C --> D[Registered format services]
D --> F{Read or write probe}
F -->|Accepted| E
F -->|Rejected by all| G[No usable I/O service]
E --> H[Data transfer]
The registry must contain the format factory before selection starts. A format module that is built but not linked or loaded cannot take part in this path. See format integration and I/O factories for registration and loading details.
References: Modules/…/itkImageIOFactory.h• L27-62 Modules/…/itkImageIOFactory.cxx• L59-109 Modules/…/itkMeshIOFactory.cxx• L29-66 Modules/…/itkTransformIOFactory.cxx• L30-48
Image I/O
Image import and export
ImageFileReader imports one file into an image pipeline. It selects an image service, reads image information, creates the output geometry, and transfers pixel data. ImageFileWriter performs the reverse path and gives the selected service the image geometry, metadata, and requested region.
The reader can use a caller-supplied service when factory selection is not suitable. When the file has more dimensions than the output image, the reader applies a direction-collapse strategy to derive the lower-dimensional physical space. Its default is identity collapse, while submatrix and guess strategies provide other choices. The reader also converts component types when the file pixel type differs from the requested output type. Negative file spacing is normalized to positive spacing by reversing the matching direction axis, while the original spacing and direction remain available in metadata.
Image series use a file list rather than one path. ImageSeriesReader combines source files into one image and checks slice size and physical spacing. It can reverse file order and retain one metadata dictionary per file. ImageSeriesWriter splits an image into output files and can use matching per-file metadata. The list order therefore connects physical image order with metadata and file names.
The import and export path is:
- The reader or writer receives a path or file list.
- The image factory selects a service for read or write mode.
- The service exchanges dimensions, physical geometry, pixel values, and supported metadata.
- The reader creates an image or the writer creates the file representation.
References: Modules/…/itkImageFileReader.h• L34-60 Modules/…/itkImageFileReader.hxx• L95-278 Modules/…/itkImageSeriesReader.h• L135-173 Modules/…/itkImageSeriesWriter.h• L186-223 Modules/…/itkImageFileWriter.h• L54-74
Image geometry and metadata
Image geometry defines the physical grid through dimensions, spacing, origin, and direction. The metadata dictionary carries named values that are not part of that grid, such as acquisition or format fields. A format service maps both groups across the file boundary when the target format supports them. The image data representation page explains the in-memory image model that receives this information.
Format behavior can normalize values during transfer. NIfTI can apply stored scaling and map vector layout and spatial conventions. DICOM services map supported tags and rescale values. NRRD and MINC map file axes, components, coordinate conventions, and typed attributes into the common image model. HDF5 keeps geometry, voxel data, and metadata in one structured image file.
Metadata is part of the I/O contract, not only an optional header view. Services must clear state before reading a new file so that a reused service does not expose values from an earlier file. MetaIO array input can also become ITK array or vector data without a second data copy when the caller transfers ownership of the read buffer.
References: Modules/…/itkNiftiImageIO.cxx• L297-616 Modules/…/itkGDCMImageIO.cxx• L446-830 Modules/…/itkNrrdImageIO.cxx• L655-797 Modules/…/itkMINCImageIO.cxx• L784-975 Modules/…/itkHDF5ImageIO.cxx• L620-706 Modules/…/itkMetaArrayReader.h• L45-135 Modules/…/itkMetaArrayReader.h• L190-213
Image format paths
Format modules give the common image path concrete rules for file layout, supported pixel content, geometry, metadata, and streaming. The reader and writer do not need format-specific logic; they use the service selected by the image factory.
Important image paths include:
- TIFF exchange maps pages, samples, palettes, resolution, tags, and supported compression. Multi-page input keeps compatible primary pages and rejects incompatible page descriptions.
- DICOM series discovery scans image objects, groups them by raw SeriesInstanceUID by default, and orders them by physical position before the series reader builds the volume. Optional series details and tag restrictions can refine that grouping. It excludes non-image DICOM objects and can scan nested directories. Small orientation rounding is accepted, but inconsistent slice orientation or position makes geometric ordering ambiguous. The default path reports an error; an explicit compatibility option permits a flagged fallback based first on instance number and then on file name.
- Bruker
2dseqimport uses companion parameter files to recover geometry, scaling, frame order, and acquisition metadata. - MINC exchange maps spatial, time, and vector dimensions into image dimensions and components. A time axis remains distinct from vector components. Single-slice and missing-axis cases use singleton image axes and preserve the expected physical direction. The format can convert between RAS and ITK's LPS convention, with a default controlled by the build setting or
ITK_MINC_IO_RAS_TO_LPS; written files record the conversion choice. The time-series tests also verify that a single-frame time axis reads as a three-dimensional image and that a time series keeps time on the fourth axis during a round trip. - MRC exchange reads and writes binary
.mrcand.recvolumes. It carries dimensions, spacing, origin, pixel mode, byte order, and anMRCHeadermetadata object. It supports streaming and updates scalar header statistics during export. - Scanco exchange reads and writes ISQ and RAD image files through a registered image factory. It maps scan dimensions and physical spacing into image geometry, and carries scan, patient, date, and calibration values through the format metadata. Extended headers can include calibration and density-rescale information.
- NRRD exchange maps domain and range axes to ITK dimensions and pixel components. It preserves typed axis labels, units, and measurement frames when the metadata is valid.
- HDF5, NIfTI, VTI, and PNG provide structured, header-plus-data, XML, and two-dimensional raster paths respectively. Each path keeps only the geometry, pixel forms, metadata, and compression that its file model supports.
See format integration and I/O factories for how a format module exposes its service and factory.
References: Modules/…/itkMINCImageIOGTest.cxx• L156-238 Modules/…/itkMINCImageIOLPSGeometryGTest.cxx• L209-258 Modules/…/itkMINCImageIO.cxx• L324-370 Modules/…/itkMINCImageIO.cxx• L387-831 Modules/…/itkMRCImageIO.cxx• L35-50 Modules/…/itkMRCImageIO.cxx• L61-227 Modules/…/itkMRCImageIO.cxx• L318-464 Modules/…/itkTIFFImageIO.cxx• L347-550 Modules/…/itkGDCMImageIO.cxx• L197-262 Modules/…/itkGDCMSeriesFileNames.cxx• L112-333 Modules/…/itkGDCMSeriesFileNamesContractGTest.cxx• L268-533 Modules/…/itkNrrdImageIO.cxx• L964-1096 Modules/…/itkPNGImageIO.cxx• L79-129 Modules/…/itkScancoImageIOFactory.h• L25-67 Modules/…/itkISQHeaderIO.cxx• L114-182 Modules/…/itkISQHeaderIO.cxx• L185-248 Modules/…/itkISQHeaderIO.cxx• L370-456
Mesh I/O
Mesh import and export
MeshFileReader imports points, cells, point data, and cell data through a selected mesh service. MeshFileWriter sends the same mesh parts to a format service, which writes only the content its file model supports.
The common mesh boundary hides differences between general mesh formats and focused formats. VTK PolyData supports points, vertices, lines, polygons, and data arrays in ASCII or binary form. SWC maps neuron samples and parent links to points and line cells. MZ3 maps a three-dimensional triangle mesh with optional point data.
Mesh round-trip checks compare point identifiers and coordinates, cell identifiers and topology, and point and cell data. The test helper can reuse the input service when the input and output extensions match. This makes the check focus on the shared mesh result rather than on byte-for-byte file equality.
Automatic write selection uses the output path. A caller can supply a mesh service directly when the path does not identify the intended format or when the format choice must not depend on the name.
References: Modules/…/itkMeshFileReader.h• L42-66 Modules/…/itkMeshFileWriter.h• L28-49 Modules/…/itkMeshFileWriter.hxx• L61-149 Modules/…/itkMeshFileTestHelper.h• L255-361 Modules/…/itkVTKPolyDataMeshIO.cxx• L85-183 Modules/…/itkSWCMeshIO.h• L33-64 Modules/…/itkMZ3MeshIO.cxx• L201-387
Spatial-object scene I/O
Scene import and export
SpatialObjectReader and SpatialObjectWriter move a scene between spatial-object data and MetaIO scene data. A scene has a root object with optional children. It keeps object types, parent-child links, transforms, properties, and supported shape or image data together.
Converters map supported object types between the scene file model and ITK spatial objects. A writer can keep image payloads in separate files when the scene needs external image data. A focused polygon XML path handles a three-dimensional polygon group and selected scene metadata, but it does not promise full support for every spatial-object type or metadata entry.
See mesh and spatial objects for the object model that scene I/O preserves.
References: Modules/…/itkSpatialObjectReader.h• L62-105 Modules/…/itkSpatialObjectWriter.h• L63-124 Modules/…/itkPolygonGroupSpatialObjectXMLFile.h• L82-114 Modules/…/itkPolygonGroupSpatialObjectXMLFile.cxx• L47-149
Transform I/O
Transform import and export
TransformFileReaderTemplate imports one or more transforms from a file. TransformIOFactoryTemplate selects a service for the parameter value type. The service reads transform types, parameters, and fixed parameters into an ordered transform list.
TransformFileWriterTemplate exports one transform or an ordered list through a service selected from the output path. A composite transform remains a top-level item when the format supports it. Float and double parameter types use matching service variants, so precision is part of the file contract. The composite helper recognizes supported dimensions from two through nine and rebuilds a composite from its ordered component list.
The default transform registry covers common affine, composite, identity, translation, rigid, similarity, scale, spline, displacement, and velocity-field types. It registers float and double variants separately across the supported dimensions and spline orders. An unregistered transform type cannot be rebuilt from a file.
This diagram shows how source data and a saved mapping move through registration and later resampling.
flowchart LR
A[Image or mesh files] --> B[Data readers]
C[Spatial-object scene file] --> D[Scene reader]
B --> E[Fixed and moving data]
D --> E
E --> F[Registration method]
F --> G[Transform]
G --> H[Transform writer]
H --> I[Transform file]
I --> J[Later resampling or registration stage]
The HDF5 transform path stores transforms in a structured file and supports compressed and uncompressed output. Its round-trip coverage includes float and double parameter values, affine transforms, displacement-field transforms, and field spacing and origin. The test also confirms that a transform with an unregistered dimension is rejected when read.
Transform format modules provide different file models behind the same boundary. The legacy text service can resolve component files listed by a composite transform. The MINC transform service reads and writes .xfm mappings in RAS or LPS form and can carry a displacement field through a companion MINC image. The factory keeps those choices outside the transform reader and writer. See format integration and I/O factories for module registration.
References: Modules/…/itkTransformFileReader.h• L27-101 Modules/…/itkTransformFileWriter.h• L29-114 Modules/…/itkTransformBase.h• L43-181 Modules/…/itkCompositeTransformIOHelper.cxx• L28-147 Modules/…/itkTransformFactoryBaseRegister.cxx• L61-204 Modules/…/itkIOTransformHDF5Test.cxx• L40-175 Modules/…/itkIOTransformHDF5Test.cxx• L178-317 Modules/…/itkIOTransformHDF5Test.cxx• L319-403 Modules/…/itkHDF5TransformIO.cxx• L38-95 Modules/…/itkTxtTransformIO.cxx• L37-100 Modules/…/itkMINCTransformIO.h• L33-110 Modules/…/itkMINCTransformIO.cxx• L63-252 Modules/…/itkMINCTransformIO.cxx• L254-466
Cross-system I/O paths
Registration data flow
Registration consumes images, point sets, and spatial objects in physical space. Their readers establish source data and geometry before a registration method compares fixed and moving inputs. The resulting transform describes the mapping between spaces and can be saved for later resampling or registration.
The important boundary is that image and object files hold source data, while a transform file holds the mapping between spaces. This keeps source data and alignment results independently reusable.
References: Modules/…/itkImageFileReader.h• L34-60 Modules/…/itkSpatialObjectReader.h• L62-105 Modules/…/itkTransformFileWriter.h• L95-114 Modules/…/itkImageRegistrationMethod.h• L29-59
Change checklist
When these files or sections are changed, remember to consider these:
- A format service change to read or write capability changes automatic factory selection in both directions.
- A Scanco factory or header change must keep ISQ and RAD detection, physical spacing, extended calibration metadata, and format registration aligned with the image reader and writer.
- A factory registration change must keep the registered service visible before a reader or writer starts selection.
- A change to image geometry transfer must preserve the relationship between dimensions, spacing, origin, direction, and metadata.
- A change to image-series handling must keep file order aligned with per-file metadata dictionaries and physical points. It must also keep slice-size validation, positive spacing, direction correction, and non-uniform-sampling reporting consistent for normal and reversed order.
- DICOM series discovery changes must keep raw SeriesInstanceUID grouping, optional series restrictions, image-only filtering, recursive scanning, geometric ordering tolerance, fallback order, and the ambiguous-ordering guard aligned with the series reader.
- DICOM image changes must keep tag spelling, private-tag policy, rescale behavior, packed single-bit data, photometric conversion, pixel spacing, generated UIDs, and compression behavior aligned between metadata and pixel transfer.
- MINC dimension changes must keep time axes, singleton missing axes, vector components, apparent dimension order, coordinate convention, and stored geometry aligned in both directions.
- MINC coordinate changes must keep the RAS/LPS setting consistent between image and transform I/O. The selected setting must remain visible in the stored
itk:RAStoLPSattribute. - MRC changes must keep extension and magic-number probing, mode-to-pixel mapping, byte order, header metadata, spacing, origin, streaming offsets, and header statistics aligned.
- Metadata inspection changes must keep non-string metadata visible through the common metadata interface.
- A mesh format change must keep supported points, cells, point data, and cell data aligned between the service and the mesh reader or writer. Round-trip helpers must compare IDs and topology as well as values.
- A spatial-object converter change must be checked against hierarchy links, object transforms, and external image payload paths.
- A transform format change must preserve transform-list order, composite assembly, float or double service availability, compression behavior, and displacement-field geometry.
- A MINC transform change must keep affine matrix orientation, concatenation order, RAS/LPS conversion, displacement-field companion paths, and inverse-field meaning aligned on read and write.
- A default transform registration change must keep the expected dimensions, spline orders, precision variants, and wrapped names aligned.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| No registered service accepts the path in the requested mode | The reader or writer cannot create an I/O service | Add or load the format module, or supply the service directly |
| A format supports reading but not writing | Import works but export fails for the same path family | Check read and write capability separately before export |
| The image has more dimensions than the output and the collapse strategy is not suitable | The output direction or physical points do not match the intended lower-dimensional image | Choose the collapse strategy deliberately and compare physical points |
| Series slices have different sizes or non-uniform positions | The volume is rejected or its slice geometry does not describe the source files | Require matching slice sizes and inspect the recorded position deviation |
| DICOM files contain duplicate positions or inconsistent orientations | Automatic series order is rejected, or an opted-in fallback produces an order that is not physically reliable | Keep the default failure guard enabled and inspect DidUseAmbiguousOrdering when compatibility fallback is allowed; small orientation rounding remains acceptable |
| DICOM pixel spacing has an invalid or incomplete value | Image geometry is rejected or receives an invalid spacing | Accept only a positive isotropic value or a valid two-value pair |
| MINC time or spatial axes are mapped to the wrong ITK axes | Time, singleton dimensions, pixel values, or physical direction move to the wrong place | Check axis order, image size, spacing, direction, and round-trip values |
| MINC RAS/LPS settings differ between image data and transforms | Images and mappings use different physical coordinate conventions | Use the same setting and check the stored itk:RAStoLPS marker |
| MRC mode, byte order, or header size is interpreted incorrectly | Pixel values or image geometry are corrupted, or streaming starts at the wrong offset | Validate the MAP marker, mode, byte order, dimensions, and header boundary |
| A target format cannot represent the source geometry or mesh content | Orientation, spacing, topology, or attached values can be lost | Check the target service's supported geometry and data model before export |
| A mesh round trip changes point or cell IDs, topology, or attached data | The output mesh is structurally different even when the file opens | Compare points, cells, point data, and cell data after reading the output |
| A Scanco header has invalid dimensions or incomplete extended data | Image geometry or calibration metadata is wrong, or the header cannot be read safely | Validate ISQ or RAD version and dimensions, and retain complete header blocks when extended calibration data is needed |
| A composite transform references missing component files | The transform list cannot be assembled | Keep component files with the master file or use a self-contained format |
| A transform dimension or parameter precision is not registered | A transform cannot be created from a file | Keep default registrations and file parameter types aligned |
| A MINC transform references an absent displacement-field companion | The .xfm file cannot reconstruct the non-linear mapping | Keep the companion .mnc file with the transform and preserve its path contract |
| HDF5 transform compression or field geometry is not preserved | The file may open but the transform changes during a round trip | Test compressed and uncompressed float and double paths and compare field spacing and origin |
| A scene converter does not support an object type | The scene cannot round-trip that object as the same spatial type | Register a converter or choose a format with native support |
Key files
| File | Why to read it |
|---|---|
| Modules/…/itkImageFileReader.h | Defines the high-level image import role and direction collapse options. |
Modules/IO/ImageBase/include/itkImageFileReader.hxx | Shows image service selection, geometry setup, metadata handoff, streaming, and pixel conversion. |
| Modules/…/itkImageFileWriter.h | Defines image export and geometry and metadata handoff. |
Modules/IO/ImageBase/src/itkImageIOFactory.cxx | Shows image service selection for read and write paths. |
Modules/IO/ImageBase/include/itkImageSeriesReader.hxx | Shows series geometry construction, slice validation, and per-file metadata handling. |
| Modules/…/itkGDCMImageIO.h | Defines DICOM image controls for metadata, rescaling, packed bit values, UIDs, and compression. |
Modules/IO/GDCM/src/itkGDCMImageIO.cxx | Illustrates DICOM probing, geometry, metadata, pixel conversion, and export policy. |
Modules/IO/GDCM/src/itkGDCMSeriesFileNames.cxx | Defines DICOM series grouping, image filtering, geometric ordering, and compatibility fallback. |
Modules/IO/GDCM/test/itkGDCMSeriesFileNamesContractGTest.cxx | Pins the observable DICOM series grouping, recursive scan, orientation tolerance, ordering fallback, image filtering, and ambiguity contract. |
| Modules/…/itkMINCImageIO.h | Defines MINC dimensions and the RAS-to-LPS coordinate option. |
Modules/IO/MINC/src/itkMINCImageIO.cxx | Shows MINC axis mapping, geometry, metadata, coordinate conversion, scaling, and compression. |
Modules/IO/MINC/test/itkMINCImageIOLPSGeometryGTest.cxx | Verifies MINC coordinate conversion defaults, environment control, and stored conversion metadata. |
| Modules/…/itkMetaArrayReader.h | Defines MetaIO array import and its array or vector output contract. |
| Modules/…/itkScancoImageIOFactory.h | Defines the Scanco image factory registration entry point used by automatic image service selection. |
Modules/IO/IOScanco/src/itkISQHeaderIO.cxx | Shows ISQ and RAD header exchange, image geometry recovery, and extended calibration metadata handling. |
| Modules/…/itkMeshFileReader.h | Defines mesh import into points, cells, and data arrays. |
| Modules/…/itkMeshFileWriter.h | Defines mesh export and direct service override. |
| Modules/…/itkMeshFileTestHelper.h | Shows the shared mesh round-trip contract for points, cells, and attached data. |
Modules/IO/MeshVTK/src/itkVTKPolyDataMeshIO.cxx | Illustrates VTK PolyData probing, topology, and point or cell data. |
| Modules/…/itkSpatialObjectReader.h | Defines scene import, hierarchy access, and converter use. |
| Modules/…/itkSpatialObjectWriter.h | Defines scene export and separate image-payload handling. |
| Modules/…/itkTransformIOBase.h | Defines the transform service boundary, ordered transform lists, and precision variants. |
Modules/IO/TransformBase/src/itkTransformFileReader.cxx | Shows transform selection, reading, and composite assembly. |
Modules/IO/TransformBase/src/itkTransformFileWriterSpecializations.cxx | Shows transform-list export and precision-aware service selection. |
Modules/IO/TransformBase/src/itkCompositeTransformIOHelper.cxx | Shows composite transform list order and reconstruction. |
Modules/IO/TransformFactory/src/itkTransformFactoryBaseRegister.cxx | Defines the default transform types, dimensions, spline orders, and parameter precisions. |
Modules/IO/TransformHDF5/test/itkIOTransformHDF5Test.cxx | Shows HDF5 transform registration, compression modes, precision variants, field geometry checks, and unregistered-type failure. |
Modules/IO/TransformHDF5/src/itkHDF5TransformIO.cxx | Illustrates structured transform-file storage behind the common transform boundary. |
Modules/IO/TransformInsightLegacy/src/itkTxtTransformIO.cxx | Illustrates text transform files and composite component paths. |
| Modules/…/itkMINCTransformIO.h | Defines MINC transform support and its coordinate convention option. |
Modules/IO/TransformMINC/src/itkMINCTransformIO.cxx | Shows MINC affine, composite, displacement-field, and RAS/LPS transform exchange. |
Modules/IO/TransformMINC/test/itkIOTransformMINCTest.cxx | Verifies MINC transform round trips for affine, composite, displacement-field, float, and double paths. |
| docs/io-format-integration.md | Explains format module registration and factory selection. |
| docs/image-data-representation.md | Explains the image geometry, pixel, and metadata model used by image I/O. |
| docs/mesh-and-spatial-objects.md | Explains the data model used by mesh and spatial-object I/O. |