CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-torchio

Tools for medical image processing with PyTorch

Overview
Eval results
Files

preprocessing.mddocs/

Preprocessing Transforms

Comprehensive preprocessing transforms for medical images including spatial transformations (resampling, cropping, padding), intensity normalization (z-score, histogram standardization), and specialized medical imaging preprocessing. These transforms prepare medical images for analysis and training.

Capabilities

Spatial Preprocessing

Spatial transforms that modify the geometry, orientation, or spatial properties of medical images while preserving anatomical relationships.

Resampling

Resamples images to specified voxel spacing, enabling standardization of resolution across different imaging protocols and scanners.

class Resample(SpatialTransform):
    """
    Resample images to specified voxel spacing.
    
    Parameters:
    - target: Target voxel spacing in mm (float or tuple of 3 floats)
    - image_interpolation: Interpolation for intensity images ('linear', 'nearest', 'bspline')
    - label_interpolation: Interpolation for label images ('nearest')
    """
    def __init__(
        self,
        target: TypeSpacing,
        image_interpolation: str = 'linear',
        label_interpolation: str = 'nearest'
    ): ...

Resize

Resizes images to specified shape, changing the number of voxels while maintaining physical spacing relationships.

class Resize(SpatialTransform):
    """
    Resize images to specified shape.
    
    Parameters:
    - target_shape: Target shape (int or tuple of 3 ints)
    - image_interpolation: Interpolation method for intensity images
    """
    def __init__(
        self,
        target_shape: TypeSpatialShape,
        image_interpolation: str = 'linear'
    ): ...

Cropping and Padding

class Crop(SpatialTransform):
    """
    Crop images to specified region.
    
    Parameters:
    - cropping: Crop specification (int, tuple, or dict)
    """
    def __init__(self, cropping: Union[int, tuple, dict]): ...

class Pad(SpatialTransform):
    """
    Pad images with specified padding.
    
    Parameters:
    - padding: Padding specification (int, tuple, or dict)
    - padding_mode: Padding mode ('constant', 'edge', 'wrap', 'empty')
    """
    def __init__(
        self,
        padding: Union[int, tuple, dict],
        padding_mode: str = 'constant'
    ): ...

class CropOrPad(SpatialTransform):
    """
    Crop or pad images to achieve target shape.
    
    Parameters:
    - target_shape: Target spatial shape
    - padding_mode: Padding mode for padding operations
    """
    def __init__(
        self,
        target_shape: TypeSpatialShape,
        padding_mode: str = 'constant'
    ): ...

Orientation and Canonical Transforms

class ToCanonical(SpatialTransform):
    """
    Reorient images to canonical orientation (RAS+).
    
    Ensures consistent orientation across all images, with:
    - Right-to-Left as first axis
    - Anterior-to-Posterior as second axis  
    - Superior-to-Inferior as third axis
    """
    def __init__(self): ...

class ToOrientation(SpatialTransform):
    """
    Reorient images to specified orientation.
    
    Parameters:
    - target: Target orientation (e.g., 'RAS', 'LPS')
    """
    def __init__(self, target: str): ...

class Transpose(SpatialTransform):
    """
    Transpose image dimensions.
    
    Parameters:
    - axes: Permutation of axes (tuple of 3 ints)
    """
    def __init__(self, axes: tuple[int, int, int]): ...

Specialized Spatial Transforms

class ToReferenceSpace(SpatialTransform):
    """
    Transform images to reference space defined by another image.
    
    Parameters:
    - reference: Reference image or path to reference image
    """
    def __init__(self, reference: Union['Image', TypePath]): ...

class CopyAffine(SpatialTransform):
    """
    Copy affine transformation from one image to others.
    
    Parameters:
    - target: Name of image to copy affine from
    """
    def __init__(self, target: str): ...

class EnsureShapeMultiple(SpatialTransform):
    """
    Ensure image shape is multiple of specified value.
    
    Parameters:
    - multiple: Value that shape dimensions should be multiple of
    """
    def __init__(self, multiple: int): ...

Usage example:

import torchio as tio

# Spatial preprocessing pipeline
spatial_preprocessing = tio.Compose([
    tio.ToCanonical(),                    # Standardize orientation
    tio.Resample(1),                      # Resample to 1mm isotropic
    tio.CropOrPad((128, 128, 64)),       # Standardize shape
    tio.EnsureShapeMultiple(16),          # Ensure shape divisible by 16
])

subject = tio.Subject(
    t1=tio.ScalarImage('t1.nii.gz'),
    seg=tio.LabelMap('segmentation.nii.gz')
)

transformed = spatial_preprocessing(subject)

Intensity Preprocessing

Intensity transforms that normalize, standardize, or modify the intensity values of medical images while preserving spatial structure.

Normalization Transforms

class ZNormalization(IntensityTransform):
    """
    Z-score normalization (zero mean, unit variance).
    
    Parameters:
    - masking_method: Method for creating mask ('brain', 'label', etc.)
    """
    def __init__(self, masking_method: str = None): ...

class RescaleIntensity(IntensityTransform):
    """
    Rescale intensities to specified range.
    
    Parameters:
    - out_min_max: Output range (tuple of min, max values)
    - percentiles: Input percentiles to use for scaling
    """
    def __init__(
        self,
        out_min_max: tuple[float, float] = (0, 1),
        percentiles: tuple[float, float] = (0.5, 99.5)
    ): ...

class HistogramStandardization(IntensityTransform):
    """
    Histogram standardization using learned landmarks.
    
    Parameters:
    - landmarks: Dictionary mapping image keys to landmark arrays
    """
    def __init__(self, landmarks: dict): ...

Intensity Manipulation

class Clamp(IntensityTransform):
    """
    Clamp intensity values to specified range.
    
    Parameters:
    - out_min_max: Output range (tuple of min, max values)
    """
    def __init__(self, out_min_max: tuple[float, float]): ...

class Mask(IntensityTransform):
    """
    Apply binary mask to images.
    
    Parameters:
    - masking_method: Masking method or mask image name
    - mask_value: Value to use for masked regions
    """
    def __init__(
        self,
        masking_method: Union[str, 'Image'],
        mask_value: float = 0
    ): ...

Advanced Intensity Transforms

class PCA(IntensityTransform):
    """
    Principal Component Analysis for multi-channel images.
    
    Parameters:
    - num_components: Number of components to keep
    """
    def __init__(self, num_components: int): ...

class To(IntensityTransform):
    """
    Convert images to specified type or device.
    
    Parameters:
    - dtype: Target data type
    - device: Target device ('cpu', 'cuda')
    """
    def __init__(
        self,
        dtype: torch.dtype = None,
        device: str = None
    ): ...

Usage example:

# Intensity preprocessing pipeline
intensity_preprocessing = tio.Compose([
    tio.RescaleIntensity(out_min_max=(0, 1)),     # Scale to [0,1]
    tio.ZNormalization(masking_method='brain'),    # Z-score with brain mask
    tio.Clamp(out_min_max=(-3, 3)),              # Clamp outliers
])

subject = tio.Subject(
    t1=tio.ScalarImage('t1.nii.gz'),
    t2=tio.ScalarImage('t2.nii.gz')
)

normalized = intensity_preprocessing(subject)

Label Preprocessing

Specialized transforms for processing segmentation and label images, including label manipulation, connectivity analysis, and label format conversions.

class OneHot(LabelTransform):
    """
    Convert labels to one-hot encoding.
    
    Parameters:
    - num_classes: Number of classes (optional, inferred if not provided)
    """
    def __init__(self, num_classes: int = None): ...

class Contour(LabelTransform):
    """
    Extract contours from label maps.
    
    Parameters:
    - radius: Radius for contour extraction
    """
    def __init__(self, radius: int = 1): ...

class RemapLabels(LabelTransform):
    """
    Remap label values according to mapping dictionary.
    
    Parameters:
    - remapping: Dictionary mapping old labels to new labels
    """
    def __init__(self, remapping: dict[int, int]): ...

class RemoveLabels(LabelTransform):
    """
    Remove specified labels by setting them to background.
    
    Parameters:
    - labels: Labels to remove (int or list of ints)
    """
    def __init__(self, labels: Union[int, list[int]]): ...

class SequentialLabels(LabelTransform):
    """
    Ensure labels are sequential starting from 0.
    """
    def __init__(self): ...

class KeepLargestComponent(LabelTransform):
    """
    Keep only the largest connected component for each label.
    """
    def __init__(self): ...

Usage example:

# Label preprocessing for segmentation task
label_preprocessing = tio.Compose([
    tio.RemapLabels({1: 1, 2: 1, 3: 2}),        # Merge some labels
    tio.KeepLargestComponent(),                   # Remove small components
    tio.SequentialLabels(),                       # Ensure sequential labels
])

subject = tio.Subject(
    image=tio.ScalarImage('image.nii.gz'),
    segmentation=tio.LabelMap('multi_label_seg.nii.gz')
)

processed = label_preprocessing(subject)

Histogram Standardization Training

Utility function for training histogram standardization landmarks from a dataset.

def train_histogram(
    subjects_dataset: SubjectsDataset,
    output_path: TypePath,
    progress: bool = True
) -> dict:
    """
    Train histogram standardization landmarks from dataset.
    
    Parameters:
    - subjects_dataset: Dataset to train landmarks from
    - output_path: Path to save landmarks
    - progress: Whether to show progress bar
    
    Returns:
    Dictionary with landmarks for each image type
    """

Usage example:

# Train histogram standardization landmarks
subjects = [...]  # List of training subjects
training_dataset = tio.SubjectsDataset(subjects)

landmarks = tio.train_histogram(
    subjects_dataset=training_dataset,
    output_path='histogram_landmarks.json'
)

# Use trained landmarks in preprocessing
hist_std = tio.HistogramStandardization(landmarks)

Install with Tessl CLI

npx tessl i tessl/pypi-torchio

docs

augmentation.md

composition.md

core-data-structures.md

data-loading.md

datasets.md

index.md

preprocessing.md

sampling.md

utilities.md

tile.json