CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-itk

Insight Toolkit for N-dimensional image processing, segmentation, and registration in medical and scientific applications

Pending
Overview
Eval results
Files

io.mddocs/reference/

Image I/O

Comprehensive I/O capabilities for reading and writing images, meshes, and transforms across 42+ file formats including medical imaging standards (DICOM, NIfTI, NRRD) and common image formats (PNG, JPEG, TIFF).

Capabilities

High-Level I/O Functions

Convenient functions for reading and writing without explicit reader/writer setup.

def imread(filename, pixel_type=None, fallback_only=False, imageio=None, series_uid=None):
    """
    Read an image from a file or series of files.
    
    Parameters:
    - filename: str, list, or Path - File path, list of files for a series, or directory for DICOM
    - pixel_type: itkCType, optional - Image pixel type to cast to when loading (e.g., itk.F, itk.UC)
    - fallback_only: bool - If True, try automatic type deduction first, use pixel_type as fallback
    - imageio: ImageIOBase, optional - Use specific ImageIOBase instance for reading
    - series_uid: str or int, optional - For DICOM directories, specify series UID (string) or integer index
    
    Returns:
    itk.Image - Loaded image
    
    Examples:
    image = itk.imread('input.png')
    image = itk.imread('input.dcm', itk.F)
    image = itk.imread('/path/to/dicom/series/', series_uid=0)
    """

def imwrite(image_or_filter, filename, compression=False, imageio=None):
    """
    Write an image or filter output to a file.
    
    Parameters:
    - image_or_filter: itk.Image or ProcessObject - Image or filter producing an image
    - filename: str or Path - Output file path
    - compression: bool - Use compression if format supports it
    - imageio: ImageIOBase, optional - Use specific ImageIOBase instance for writing
    
    Examples:
    itk.imwrite(image, 'output.png')
    itk.imwrite(image, 'output.nii.gz', compression=True)
    """

def meshread(filename, pixel_type=None, fallback_only=False):
    """
    Read a mesh from a file.
    
    Parameters:
    - filename: str or Path - Path to mesh file
    - pixel_type: itkCType, optional - Pixel type for mesh data
    - fallback_only: bool - Try automatic type deduction first
    
    Returns:
    itk.Mesh - Loaded mesh
    """

def meshwrite(mesh, filename, compression=False):
    """
    Write a mesh to a file.
    
    Parameters:
    - mesh: itk.Mesh - Mesh to write
    - filename: str or Path - Output file path
    - compression: bool - Use compression if supported
    """

def transformread(filename):
    """
    Read transforms from a file (typically .h5 or .txt).
    
    Parameters:
    - filename: str or Path - Path to transform file
    
    Returns:
    list of itk.Transform - List of loaded transforms
    """

def transformwrite(transforms, filename, compression=False):
    """
    Write one or more transforms to a file.
    
    Parameters:
    - transforms: itk.Transform or list - Single transform or list of transforms
    - filename: str or Path - Output file path
    - compression: bool - Use compression if supported
    """

Image File Readers

Filter-based readers for fine-grained control over image loading.

class ImageFileReader:
    """
    Read an image from a file with full control over I/O.
    
    Template parameter:
    - image_type: Image type
    """
    
    def SetFileName(self, filename):
        """
        Set the filename to read.
        
        Parameters:
        - filename: str or Path
        """
    
    def GetFileName(self):
        """Get the current filename."""
    
    def SetImageIO(self, imageio):
        """
        Set specific ImageIO instance to use.
        
        Parameters:
        - imageio: ImageIOBase instance
        """
    
    def GetImageIO(self):
        """Get the ImageIO instance being used."""
    
    def Update(self):
        """Execute the reading operation."""
    
    def GetOutput(self):
        """
        Get the loaded image.
        
        Returns:
        itk.Image
        """
    
    def UpdateLargestPossibleRegion(self):
        """Update and read the entire image."""

class ImageSeriesReader:
    """
    Read a series of 2D images as a 3D volume.
    
    Template parameter:
    - image_type: 3D Image type
    """
    
    def SetFileNames(self, filenames):
        """
        Set the list of filenames to read.
        
        Parameters:
        - filenames: list of str - Ordered list of 2D image filenames
        """
    
    def GetFileNames(self):
        """Get the list of filenames."""
    
    def SetImageIO(self, imageio):
        """Set specific ImageIO instance."""
    
    def Update(self):
        """Execute the reading operation."""
    
    def GetOutput(self):
        """Get the assembled 3D image."""

Image File Writers

Filter-based writers for fine-grained control over image saving.

class ImageFileWriter:
    """
    Write an image to a file with full control over I/O.
    
    Template parameter:
    - image_type: Image type
    """
    
    def SetFileName(self, filename):
        """
        Set the filename to write.
        
        Parameters:
        - filename: str or Path
        """
    
    def GetFileName(self):
        """Get the current filename."""
    
    def SetInput(self, image):
        """
        Set the image to write.
        
        Parameters:
        - image: itk.Image
        """
    
    def SetImageIO(self, imageio):
        """
        Set specific ImageIO instance to use.
        
        Parameters:
        - imageio: ImageIOBase instance
        """
    
    def SetUseCompression(self, use_compression):
        """
        Enable/disable compression.
        
        Parameters:
        - use_compression: bool
        """
    
    def GetUseCompression(self):
        """Check if compression is enabled."""
    
    def Update(self):
        """Execute the writing operation."""
    
    def Write(self):
        """Execute the writing operation (alias for Update)."""

class ImageSeriesWriter:
    """
    Write a 3D image as a series of 2D images.
    
    Template parameter:
    - image_type: 3D Image type
    """
    
    def SetFileNames(self, filenames):
        """
        Set the list of output filenames.
        
        Parameters:
        - filenames: list of str - Ordered list of 2D output filenames
        """
    
    def SetInput(self, image):
        """Set the 3D image to write."""
    
    def Update(self):
        """Execute the writing operation."""

Transform I/O

Reading and writing geometric transforms.

class TransformFileReader:
    """
    Read transforms from a file.
    
    Template parameter:
    - scalar_type: type (typically double)
    """
    
    def SetFileName(self, filename):
        """Set the filename to read."""
    
    def Update(self):
        """Execute the reading operation."""
    
    def GetTransformList(self):
        """
        Get the list of loaded transforms.
        
        Returns:
        list of itk.Transform
        """

class TransformFileWriter:
    """
    Write transforms to a file.
    
    Template parameter:
    - scalar_type: type (typically double)
    """
    
    def SetFileName(self, filename):
        """Set the filename to write."""
    
    def SetInput(self, transform):
        """
        Set the transform to write.
        
        Parameters:
        - transform: itk.Transform or CompositeTransform
        """
    
    def AddTransform(self, transform):
        """
        Add a transform to the list to write.
        
        Parameters:
        - transform: itk.Transform
        """
    
    def Update(self):
        """Execute the writing operation."""

Mesh I/O

Reading and writing mesh data structures.

class MeshFileReader:
    """
    Read a mesh from a file.
    
    Template parameter:
    - mesh_type: Mesh type
    """
    
    def SetFileName(self, filename):
        """Set the filename to read."""
    
    def Update(self):
        """Execute the reading operation."""
    
    def GetOutput(self):
        """
        Get the loaded mesh.
        
        Returns:
        itk.Mesh
        """

class MeshFileWriter:
    """
    Write a mesh to a file.
    
    Template parameter:
    - mesh_type: Mesh type
    """
    
    def SetFileName(self, filename):
        """Set the filename to write."""
    
    def SetInput(self, mesh):
        """
        Set the mesh to write.
        
        Parameters:
        - mesh: itk.Mesh
        """
    
    def Update(self):
        """Execute the writing operation."""

DICOM Utilities

DICOM series handling and metadata access.

class GDCMSeriesFileNames:
    """
    Generate filenames for DICOM series using GDCM library.
    """
    
    def SetDirectory(self, directory):
        """
        Set the directory containing DICOM files.
        
        Parameters:
        - directory: str or Path
        """
    
    def GetSeriesUIDs(self):
        """
        Get list of series UIDs found in directory.
        
        Returns:
        list of str - Series instance UIDs
        """
    
    def GetFileNames(self, series_uid):
        """
        Get ordered filenames for a specific series.
        
        Parameters:
        - series_uid: str - Series instance UID
        
        Returns:
        list of str - Ordered list of DICOM filenames
        """
    
    def SetUseSeriesDetails(self, use_details):
        """
        Use detailed series identification.
        
        Parameters:
        - use_details: bool
        """
    
    def SetRecursive(self, recursive):
        """
        Enable/disable recursive directory search.
        
        Parameters:
        - recursive: bool
        """

class GDCMImageIO:
    """
    DICOM image I/O using GDCM library.
    """
    
    def CanReadFile(self, filename):
        """
        Check if file can be read as DICOM.
        
        Parameters:
        - filename: str
        
        Returns:
        bool
        """
    
    def GetMetaDataDictionary(self):
        """
        Get DICOM metadata dictionary.
        
        Returns:
        MetaDataDictionary
        """

ImageIO Base Classes

Low-level ImageIO objects for specific file formats.

class PNGImageIO:
    """PNG format I/O."""

class JPEGImageIO:
    """JPEG format I/O."""

class TIFFImageIO:
    """TIFF format I/O."""

class BMPImageIO:
    """BMP format I/O."""

class NiftiImageIO:
    """NIfTI format I/O (.nii, .nii.gz)."""

class NrrdImageIO:
    """NRRD format I/O (.nrrd, .nhdr)."""

class MetaImageIO:
    """MetaImage format I/O (.mha, .mhd)."""

class VTKImageIO:
    """VTK image format I/O (.vtk)."""

class HDF5ImageIO:
    """HDF5 format I/O."""

class MRCImageIO:
    """MRC format I/O (electron microscopy)."""

class GiplImageIO:
    """GIPL format I/O."""

class LSMImageIO:
    """LSM (Zeiss) format I/O."""

class BioRadImageIO:
    """Bio-Rad format I/O."""

class Bruker2dseqImageIO:
    """Bruker 2dseq format I/O."""

class StimulateImageIO:
    """Stimulate format I/O."""

MeshIO Base Classes

Low-level MeshIO objects for specific mesh formats.

class BYUMeshIO:
    """BYU mesh format I/O."""

class OBJMeshIO:
    """Wavefront OBJ format I/O."""

class OFFMeshIO:
    """OFF mesh format I/O."""

class VTKPolyDataMeshIO:
    """VTK polydata mesh format I/O."""

class FreeSurferAsciiMeshIO:
    """FreeSurfer ASCII mesh format I/O."""

class FreeSurferBinaryMeshIO:
    """FreeSurfer binary mesh format I/O."""

class GiftiMeshIO:
    """GIfTI mesh format I/O."""

Usage Examples

Reading Images

import itk

# Simple reading
image = itk.imread('input.png')

# Read with specific pixel type
image_float = itk.imread('input.png', itk.F)

# Read DICOM series
dicom_image = itk.imread('/path/to/dicom/series/')

# Read specific DICOM series by index
dicom_image = itk.imread('/path/to/dicom/series/', series_uid=0)

# Using ImageFileReader for more control
ImageType = itk.Image[itk.F, 2]
reader = itk.ImageFileReader[ImageType].New()
reader.SetFileName('input.png')
reader.Update()
image = reader.GetOutput()

Writing Images

import itk

# Simple writing
itk.imwrite(image, 'output.png')

# Write with compression
itk.imwrite(image, 'output.nii.gz', compression=True)

# Write filter output directly
filtered = itk.median_image_filter(image, radius=2)
itk.imwrite(filtered, 'filtered.png')

# Using ImageFileWriter for more control
ImageType = itk.Image[itk.F, 2]
writer = itk.ImageFileWriter[ImageType].New()
writer.SetFileName('output.png')
writer.SetInput(image)
writer.SetUseCompression(True)
writer.Update()

Reading DICOM Series

import itk

# Automatic series detection
names_generator = itk.GDCMSeriesFileNames.New()
names_generator.SetDirectory('/path/to/dicom/series/')

series_uids = names_generator.GetSeriesUIDs()
print(f"Found {len(series_uids)} series")

# Read first series
if len(series_uids) > 0:
    filenames = names_generator.GetFileNames(series_uids[0])
    
    ImageType = itk.Image[itk.SS, 3]  # 3D signed short
    reader = itk.ImageSeriesReader[ImageType].New()
    reader.SetFileNames(filenames)
    
    dicom_io = itk.GDCMImageIO.New()
    reader.SetImageIO(dicom_io)
    
    reader.Update()
    image = reader.GetOutput()

Writing Image Series

import itk

# Write 3D image as 2D slices
ImageType3D = itk.Image[itk.UC, 3]
ImageType2D = itk.Image[itk.UC, 2]

# Generate output filenames
filenames = [f'slice_{i:04d}.png' for i in range(image.GetLargestPossibleRegion().GetSize()[2])]

writer = itk.ImageSeriesWriter[ImageType3D, ImageType2D].New()
writer.SetInput(image)
writer.SetFileNames(filenames)
writer.Update()

Reading and Writing Transforms

import itk

# Read transforms
transforms = itk.transformread('transform.h5')
print(f"Loaded {len(transforms)} transform(s)")

# Use first transform
if len(transforms) > 0:
    transform = transforms[0]

# Write transform
itk.transformwrite(transform, 'output_transform.h5')

# Write multiple transforms
itk.transformwrite([transform1, transform2], 'composite.h5')

# Using TransformFileReader/Writer
reader = itk.TransformFileReaderTemplate[itk.D].New()
reader.SetFileName('transform.h5')
reader.Update()
transform_list = reader.GetTransformList()

writer = itk.TransformFileWriterTemplate[itk.D].New()
writer.SetFileName('output.h5')
writer.SetInput(transform)
writer.Update()

Reading and Writing Meshes

import itk

# Simple mesh I/O
mesh = itk.meshread('input.vtk')
itk.meshwrite(mesh, 'output.obj')

# Using MeshFileReader for more control
MeshType = itk.Mesh[itk.F, 3]
reader = itk.MeshFileReader[MeshType].New()
reader.SetFileName('input.vtk')
reader.Update()
mesh = reader.GetOutput()

# Using MeshFileWriter
writer = itk.MeshFileWriter[MeshType].New()
writer.SetFileName('output.vtk')
writer.SetInput(mesh)
writer.Update()

Format-Specific ImageIO

import itk

# Use specific ImageIO for reading
ImageType = itk.Image[itk.UC, 2]
reader = itk.ImageFileReader[ImageType].New()

png_io = itk.PNGImageIO.New()
reader.SetImageIO(png_io)
reader.SetFileName('input.png')
reader.Update()

# Check if ImageIO can read a file
nifti_io = itk.NiftiImageIO.New()
if nifti_io.CanReadFile('image.nii.gz'):
    print("Can read as NIfTI")

Supported Formats

Image Formats

  • Medical: DICOM (.dcm), NIfTI (.nii, .nii.gz), NRRD (.nrrd, .nhdr), MetaImage (.mha, .mhd), Analyze (.hdr, .img)
  • Common: PNG (.png), JPEG (.jpg, .jpeg), TIFF (.tif, .tiff), BMP (.bmp)
  • Scientific: HDF5 (.h5, .hdf5), VTK (.vtk), MRC (.mrc), GIPL (.gipl)
  • Microscopy: LSM (Zeiss), Bio-Rad, Bruker 2dseq
  • Other: Stimulate, GE (GE4, GE5, GEAdw), IPL, MINC, JPEG2000

Mesh Formats

  • BYU (.byu)
  • Wavefront OBJ (.obj)
  • OFF (.off)
  • VTK polydata (.vtk)
  • FreeSurfer (ASCII and binary)
  • GIfTI (.gii)

Transform Formats

  • HDF5 (.h5)
  • Text (.txt)
  • MatrixOffsetTransformBase (.mat)

Install with Tessl CLI

npx tessl i tessl/pypi-itk@5.4.1

docs

index.md

tile.json