### Setup Development Environment Source: https://github.com/torchio-project/torchio/blob/main/CONTRIBUTING.md Use the 'just setup' command to install uv (if not found) and then install TorchIO and its development dependencies within a virtual environment. ```bash just setup ``` -------------------------------- ### Install TorchIO with uv Source: https://github.com/torchio-project/torchio/blob/main/docs/getting-started.md Use this command to install the TorchIO package using the uv package manager. ```bash uv add torchio ``` -------------------------------- ### Install TorchIO Source: https://context7.com/torchio-project/torchio/llms.txt Install TorchIO using pip or conda. Optional extras can be included for enhanced functionality. ```bash pip install torchio ``` ```bash pip install "torchio[plot,csv]" ``` ```bash conda install -c conda-forge torchio ``` ```bash uv add torchio ``` -------------------------------- ### Install TorchIO with pip Source: https://github.com/torchio-project/torchio/blob/main/docs/getting-started.md Use this command to install the TorchIO package using pip. ```bash pip install torchio ``` -------------------------------- ### Install TorchIO with optional extras using uv Source: https://github.com/torchio-project/torchio/blob/main/docs/getting-started.md Install TorchIO with optional 'plot' and 'csv' extras using the uv package manager. ```bash uv add torchio --extra plot --extra csv ``` -------------------------------- ### Install TorchIO with optional extras using pip Source: https://github.com/torchio-project/torchio/blob/main/docs/getting-started.md Install TorchIO with optional 'plot' and 'csv' extras using pip. ```bash pip install "torchio[plot,csv]" ``` -------------------------------- ### Install Slicer Preview with Homebrew Source: https://github.com/torchio-project/torchio/blob/main/docs/interfaces/slicer.md Use this command to install the preview version of 3D Slicer on macOS using Homebrew. ```bash brew tap homebrew/cask-versions && brew cask install slicer-preview ``` -------------------------------- ### Install TorchIO with conda Source: https://github.com/torchio-project/torchio/blob/main/docs/getting-started.md Use this command to install the TorchIO package from the conda-forge channel. ```bash conda install -c conda-forge torchio ``` -------------------------------- ### RemapLabels Usage Example Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/preprocessing/RemapLabels.md This example demonstrates how to use the `RemapLabels` transform to group existing labels into new categories. ```APIDOC ## RemapLabels This transform allows remapping of label values in an image to new values. ### Usage ```python import torchio as tio # Assume 'subject' is a loaded TorchIO subject with a segmentation image # Example setup: subject = tio.datasets.FPG() subject.remove_image('t1') # Define label groups and create a remapping dictionary background_labels = (0, 1, 2, 3, 4) csf_labels = (5, 12, 16, 47, 52, 53) white_matter_labels = ( 45, 46, 66, 67, 81, 82, 83, 84, 85, 86, 87, 89, 90, 91, 92, 93, 94, ) not_gray_matter_labels = ( background_labels + csf_labels + white_matter_labels ) gray_matter_labels = [ label for label in subject.GIF_COLORS if label not in not_gray_matter_labels ] labels_groups = ( background_labels, gray_matter_labels, white_matter_labels, csf_labels, ) remapping = {} for target, labels in enumerate(labels_groups): for label in labels: remapping[label] = target # Instantiate and apply the transform parcellation_to_tissues = tio.RemapLabels(remapping) tissues = parcellation_to_tissues(subject).seg subject.add_image(tissues, 'remapped') # Optional: Plot the result # subject.plot() ``` ### Parameters - **remapping** (dict) - A dictionary where keys are the original label values and values are the new label values. ``` -------------------------------- ### Basic TorchIO 'Hello, World!' Example Source: https://github.com/torchio-project/torchio/blob/main/docs/getting-started.md Demonstrates loading 3D images, applying preprocessing and augmentation transforms, and creating training batches using SubjectsDataset and SubjectsLoader. Images can be loaded from files or created from tensors. ```python import torch import torchio as tio # Each instance of tio.Subject is passed arbitrary keyword arguments. # Typically, these arguments will be instances of tio.Image subject_a = tio.Subject( t1=tio.ScalarImage('subject_a.nii.gz'), label=tio.LabelMap('subject_a.nii'), diagnosis='positive', age=36, ) # Image files can be in any format supported by SimpleITK or NiBabel, including DICOM subject_b = tio.Subject( t1=tio.ScalarImage('subject_b_dicom_folder/'), label=tio.LabelMap('subject_b_seg.nrrd'), diagnosis='negative', age=24, ) # Images may also be created using PyTorch tensors or NumPy arrays tensor_4d = torch.rand(4, 100, 100, 100) subject_c = tio.Subject( t1=tio.ScalarImage(tensor=tensor_4d), label=tio.LabelMap(tensor=(tensor_4d > 0.5)), diagnosis='negative', age=19, ) subjects_list = [ subject_a, subject_b, subject_c, ] # Let's use one preprocessing transform and one augmentation transform # This transform will be applied only to scalar images: rescale = tio.RescaleIntensity(out_min_max=(0, 1)) # As RandomAffine is faster then RandomElasticDeformation, we choose to # apply RandomAffine 80% of the times and RandomElasticDeformation the rest # Also, there is a 25% chance that none of them will be applied spatial = tio.OneOf({ tio.RandomAffine(): 0.8, tio.RandomElasticDeformation(): 0.2, }, p=0.75, ) # Transforms can be composed as in torchvision.transforms transforms = [rescale, spatial] transform = tio.Compose(transforms) # SubjectsDataset is a subclass of torch.data.utils.Dataset subjects_dataset = tio.SubjectsDataset(subjects_list, transform=transform) # Images are processed in parallel thanks to a SubjectsLoader # (which inherits from torch.utils.data.DataLoader) training_loader = tio.SubjectsLoader( subjects_dataset, batch_size=4, num_workers=4, shuffle=True, ) # Training epoch for subjects_batch in training_loader: inputs = subjects_batch['t1'][tio.DATA] target = subjects_batch['label'][tio.DATA] ``` -------------------------------- ### CropOrPad Usage Example Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/preprocessing/CropOrPad.md This example demonstrates how to use the CropOrPad transform to resize an image to a specific spatial dimension. The transform can be applied to a single image or within a Subject. ```APIDOC ## CropOrPad Transform ### Description The `CropOrPad` transform resizes an image to a target size. If the image is larger than the target size, it will be cropped. If it is smaller, it will be padded with zeros. This is useful for ensuring all images in a dataset have the same dimensions for processing. ### Parameters - **size** (tuple of int or int): The target size in spatial dimensions (z, y, x). If a single integer is provided, it will be applied to all dimensions. ### Example ```python import torchio as tio # Load a sample image t1 = tio.datasets.Colin27().t1 # Define the target size (e.g., 512x512x32) crop_pad_transform = tio.CropOrPad((512, 512, 32)) # Apply the transform to the image t1_resized = crop_pad_transform(t1) # Alternatively, apply within a Subject subject = tio.Subject(original_image=t1, resized_image=t1_resized) # Visualize the results (optional) # subject.plot() ``` ### Notes - The transform operates on the spatial dimensions of the image. - Padding is done using zeros by default. - Cropping is performed from the center of the image. ``` -------------------------------- ### Apply Mask Transform Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/preprocessing/Mask.md This example demonstrates how to create a `Mask` transform and apply it to a subject's image. It first loads a sample subject, removes an image, creates a mask based on another image, applies the mask, and then adds the masked image back to the subject for visualization. ```python import torchio as tio subject = tio.datasets.Colin27() subject.remove_image('head') mask = tio.Mask('brain') masked = mask(subject) subject.add_image(masked.t1, 'Masked') subject.plot() ``` -------------------------------- ### Applying RandomGamma Augmentation Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/augmentation/RandomGamma.md This example demonstrates how to apply the RandomGamma transform with specified log_gamma values to a subject's image and visualize the results. It shows applying both negative and positive log_gamma values. ```python import torchio as tio subject = tio.datasets.FPG() subject.remove_image('seg') transform = tio.RandomGamma(log_gamma=(-0.3, -0.3)) transformed = transform(subject) subject.add_image(transformed.t1, 'log -0.3') transform = tio.RandomGamma(log_gamma=(0.3, 0.3)) transformed = transform(subject) subject.add_image(transformed.t1, 'log 0.3') subject.plot() ``` -------------------------------- ### Remap Labels Example Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/preprocessing/RemapLabels.md This example shows how to use RemapLabels to group various anatomical labels into broader categories. It defines groups for background, CSF, white matter, and gray matter, then creates a remapping dictionary to apply these groups to a subject's segmentation. ```python import torchio as tio subject = tio.datasets.FPG() subject.remove_image('t1') background_labels = (0, 1, 2, 3, 4) csf_labels = (5, 12, 16, 47, 52, 53) white_matter_labels = ( 45, 46, 66, 67, 81, 82, 83, 84, 85, 86, 87, 89, 90, 91, 92, 93, 94, ) not_gray_matter_labels = ( background_labels + csf_labels + white_matter_labels ) gray_matter_labels = [ label for label in subject.GIF_COLORS if label not in not_gray_matter_labels ] labels_groups = ( background_labels, gray_matter_labels, white_matter_labels, csf_labels, ) remapping = {} for target, labels in enumerate(labels_groups): for label in labels: remapping[label] = target parcellation_to_tissues = tio.RemapLabels(remapping) tissues = parcellation_to_tissues(subject).seg subject.add_image(tissues, 'remapped') subject.plot() ``` -------------------------------- ### Clamp Transform Usage Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/preprocessing/Clamp.md Example of how to use the `Clamp` transform to limit image intensity values. ```APIDOC ## Clamp Transform ### Description Limits the intensity values of an image to a specified range. ### Method Signature ```python Clamp(out_min: Union[float, int, NoneType] = -inf, out_max: Union[float, int, NoneType] = inf, **kwargs) ``` ### Parameters * **out_min** (float, int, optional) - The minimum value to clamp to. Defaults to negative infinity. * **out_max** (float, int, optional) - The maximum value to clamp to. Defaults to positive infinity. ### Example ```python import torchio as tio # Load a sample image subject = tio.datasets.Slicer('CTChest') ct = subject.CT_chest # Define the clamping range (e.g., Hounsfield units for CT) HOUNSFIELD_AIR, HOUNSFIELD_BONE = -1000, 1000 # Create the Clamp transform clamp = tio.Clamp(out_min=HOUNSFIELD_AIR, out_max=HOUNSFIELD_BONE) # Apply the transform ct_clamped = clamp(ct) # Add the clamped image to the subject and plot subject.add_image(ct_clamped, 'Clamped') subject.plot() ``` ``` -------------------------------- ### Apply RandomAffine Transform Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/augmentation/RandomAffine.md Instantiate the RandomAffine transform and apply it to a subject's image. This example demonstrates a basic usage with default parameters. ```python import torchio as tio subject = tio.datasets.Slicer('CTChest') ct = subject.CT_chest transform = tio.RandomAffine() ct_transformed = transform(ct) subject.add_image(ct_transformed, 'Transformed') subject.plot() ``` -------------------------------- ### Mask Transform Usage Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/preprocessing/Mask.md Example demonstrating how to use the Mask transform to mask an image within a subject. ```APIDOC ## Mask Transform ### Description Applies a mask to an image. The mask can be specified by an image name within the subject or by providing a mask image directly. ### Method `__call__` ### Parameters - **mask_image** (Image or str): The mask image or the name of the mask image in the subject. If a string is provided, it is assumed to be the name of an image in the subject. ### Request Example ```python import torchio as tio # Assuming 'subject' is a loaded TorchIO subject with an image named 'brain' mask_transform = tio.Mask('brain') masked_subject = mask_transform(subject) ``` ### Response Returns a new Subject with the masked image applied. ``` -------------------------------- ### Generate Synthetic Image from Labels Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/augmentation/RandomLabelsToImage.md This example demonstrates how to use RandomLabelsToImage to create a synthetic image from a label map. It first loads a dataset, extracts the label map, removes other modalities, applies resampling and blurring, and then generates the synthetic image. The plot() method visualizes the result. ```python import torch import torchio as tio torch.manual_seed(42) colin = tio.datasets.Colin27(2008) label_map = colin.cls colin.remove_image('t1') colin.remove_image('t2') colin.remove_image('pd') downsample = tio.Resample(1) blurring_transform = tio.RandomBlur(std=0.6) create_synthetic_image = tio.RandomLabelsToImage( image_key='synthetic', ignore_background=True, ) transform = tio.Compose(( downsample, create_synthetic_image, blurring_transform, )) colin_synth = transform(colin) colin_synth.plot() ``` -------------------------------- ### Applying CropOrPad to an Image Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/preprocessing/CropOrPad.md Demonstrates how to use the CropOrPad transform to resize a medical image to a specific spatial dimension. This is useful for ensuring consistent input sizes for deep learning models. The example visualizes the original and transformed images. ```python import torchio as tio t1 = tio.datasets.Colin27().t1 crop_pad = tio.CropOrPad((512, 512, 32)) t1_pad_crop = crop_pad(t1) subject = tio.Subject(t1=t1, crop_pad=t1_pad_crop) subject.plot() ``` -------------------------------- ### Downsample Image using Resample Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/preprocessing/Resample.md Use the `Resample` transform to downsample an image to a target resolution. This example demonstrates downsampling a T1-weighted image and adding it back to the subject for visualization. ```python import torchio as tio subject = tio.datasets.FPG() subject.remove_image('seg') resample = tio.Resample(8) t1_resampled = resample(subject.t1) subject.add_image(t1_resampled, 'Downsampled') subject.plot() ``` -------------------------------- ### Apply Random Affine and Elastic Deformation Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/augmentation/RandomAffineElasticDeformation.md This example demonstrates how to apply a RandomAffineElasticDeformation to a medical image. It initializes the transform with specific elastic deformation parameters and then applies it to a loaded image, adding the transformed image back to the subject for visualization. ```python import torchio as tio subject = tio.datasets.Slicer('CTChest') ct = subject.CT_chest elastic_kwargs = {'max_displacement': (17, 12, 2)} transform = tio.RandomAffineElasticDeformation(elastic_kwargs=elastic_kwargs) ct_transformed = transform(ct) subject.add_image(ct_transformed, 'Transformed') subject.plot() ``` -------------------------------- ### Create Feature Branch Source: https://github.com/torchio-project/torchio/blob/main/CONTRIBUTING.md Create a new branch for your local development, using the issue number for reference. For example, for issue number 55, use '55-name-of-your-bugfix-or-feature'. ```bash git checkout -b 55-name-of-your-bugfix-or-feature ``` -------------------------------- ### Apply RandomAffine Transform to Different Data Types Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/index.md Demonstrates applying a RandomAffine transform to PyTorch tensors, NumPy arrays, and TorchIO Subjects. Ensure TorchIO and NumPy are installed. ```python >>> import torch >>> import numpy as np >>> import torchio as tio >>> affine_transform = tio.RandomAffine() >>> tensor = torch.rand(1, 256, 256, 159) >>> transformed_tensor = affine_transform(tensor) >>> type(transformed_tensor) >>> array = np.random.rand(1, 256, 256, 159) >>> transformed_array = affine_transform(array) >>> type(transformed_array) >>> subject = tio.datasets.Colin27() >>> transformed_subject = affine_transform(subject) >>> transformed_subject Subject(Keys: ('t1', 'head', 'brain'); images: 3) ``` -------------------------------- ### Resample Transform Usage Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/preprocessing/Resample.md Example of how to use the Resample transform to change the spatial resolution of an image. The transform takes a target resolution as an argument. ```APIDOC ## Resample Transform ### Description Resamples an image to a new spatial resolution. ### Parameters - **resolution** (float or tuple of floats) - The target resolution in the same units as the input image spacing. If a single float is provided, it will be used for all dimensions. If a tuple is provided, it must match the number of dimensions of the image. ### Example ```python import torchio as tio # Load a subject and remove segmentation subject = tio.datasets.FPG() subject.remove_image('seg') # Create a Resample transform with a target resolution of 8 resample = tio.Resample(8) # Apply the transform to the T1 image t1_resampled = resample(subject.t1) # Add the resampled image back to the subject and plot subject.add_image(t1_resampled, 'Downsampled') subject.plot() ``` ``` -------------------------------- ### Serve Documentation Source: https://github.com/torchio-project/torchio/blob/main/CONTRIBUTING.md Build, serve, and automatically rebuild the documentation as you make changes. The documentation will reload in the browser upon modification. ```bash just serve-docs ``` -------------------------------- ### Build Documentation Source: https://github.com/torchio-project/torchio/blob/main/CONTRIBUTING.md Build the project documentation locally to verify any changes made to documentation files or docstrings. ```bash just build-docs ``` -------------------------------- ### RandomGamma Initialization and Usage Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/augmentation/RandomGamma.md This snippet demonstrates how to initialize and use the RandomGamma transform. It shows applying gamma correction with specified log_gamma values and visualizing the results. ```APIDOC ## RandomGamma ### Description Applies a random gamma correction to the input image. ### Parameters - **log_gamma** (tuple of float, optional): Range of gamma values to sample from. Defaults to `(-0.2, 0.2)`. ### Example ```python import torchio as tio # Initialize with a specific log_gamma range transform = tio.RandomGamma(log_gamma=(-0.3, 0.3)) # Apply the transform to a subject transformed_subject = transform(subject) ``` ### Usage Example ```python import torchio as tio subject = tio.datasets.FPG() subject.remove_image('seg') # Apply with negative log_gamma transform_neg = tio.RandomGamma(log_gamma=(-0.3, -0.3)) transformed_neg = transform_neg(subject) subject.add_image(transformed_neg.t1, 'log -0.3') # Apply with positive log_gamma transform_pos = tio.RandomGamma(log_gamma=(0.3, 0.3)) transformed_pos = transform_pos(subject) subject.add_image(transformed_pos.t1, 'log 0.3') # Visualize the results subject.plot() ``` ``` -------------------------------- ### Clone TorchIO Repository Source: https://github.com/torchio-project/torchio/blob/main/CONTRIBUTING.md Clone your forked TorchIO repository locally to begin development. Replace 'your_github_username_here' with your actual GitHub username. ```bash git clone git@github.com:your_github_username_here/torchio.git cd torchio ``` -------------------------------- ### Load Built-in TorchIO Datasets Source: https://context7.com/torchio-project/torchio/llms.txt Instantiate various downloadable 3D medical image datasets provided by TorchIO. These return Subject instances ready for use in pipelines. Ensure correct paths and download flags are set for datasets like IXITiny and OrganMNIST3D. ```python import torchio as tio # Colin27: high-resolution MRI atlas (T1, head mask, brain mask) colin = tio.datasets.Colin27() print(colin) # Colin27(Keys: ('t1', 'head', 'brain'); images: 3) # FPG: T1-weighted MRI with segmentation fpg = tio.datasets.FPG() print(fpg) # 3D Slicer sample datasets (CT, MRI, etc.) ct_subject = tio.datasets.Slicer('CTChest') mri_subject = tio.datasets.Slicer('MRHead') # IXI Tiny: subset of IXI dataset for quick experiments ixi_tiny = tio.datasets.IXITiny( root='/tmp/ixi', download=True, ) subject = ixi_tiny[0] print(subject.keys()) # MedMNIST 3D organ_dataset = tio.datasets.OrganMNIST3D( split='train', root='/tmp/medmnist', download=True, ) ``` -------------------------------- ### Commit and Push Changes Source: https://github.com/torchio-project/torchio/blob/main/CONTRIBUTING.md Stage all changes, commit them with a descriptive message, and push the branch to your GitHub repository. Refer to the provided links for advice on writing good commit messages. ```bash git add . git commit -m "Fix nasty bug" git push origin 55-name-of-your-bugfix-or-feature ``` -------------------------------- ### Inspect Image Metadata with tiohd Source: https://context7.com/torchio-project/torchio/llms.txt Employ the `tiohd` command-line tool to display detailed metadata of a NIfTI image, including shape, spacing, orientation, data type, and memory usage. ```bash # Print image metadata (shape, spacing, orientation, dtype, memory) tiohd t1.nii.gz # ScalarImage(shape: (1, 181, 217, 181); spacing: (1.00, 1.00, 1.00); # orientation: RAS+; dtype: torch.FloatTensor; memory: 27.1 MiB) ``` -------------------------------- ### Compose Transforms with Probabilities Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/index.md Shows how to compose multiple transforms, including probabilistic application of spatial transforms using OneOf. This allows for creating complex augmentation pipelines. ```python >>> import torchio as tio >>> spatial_transforms = { ... tio.RandomElasticDeformation(): 0.2, ... tio.RandomAffine(): 0.8, ... } >>> transform = tio.Compose([ ... tio.OneOf(spatial_transforms, p=0.5), ... tio.RescaleIntensity(out_min_max=(0, 1)), ... ]) ``` -------------------------------- ### Apply Random Affine Transform with tiotr Source: https://context7.com/torchio-project/torchio/llms.txt Use the `tiotr` command-line tool to apply a random affine transform to a NIfTI image. Specify the input and output file paths, transform arguments, and a random seed for reproducibility. ```bash # Apply a random affine transform and save the result tiotr input.nii.gz RandomAffine output.nii.gz \ --kwargs "degrees=15 scales=0.1" \ --seed 42 ``` -------------------------------- ### Remove Specific Labels from Label Map Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/preprocessing/RemoveLabels.md This example demonstrates how to use the RemoveLabels transform to remove several anatomical structures from a label map, effectively isolating the brain. It involves loading a dataset, defining labels to remove by name, converting names to label values, applying the transform, and adding the resulting image back to the dataset. ```python import torchio as tio colin = tio.datasets.Colin27(2008) label_map = colin.cls colin.remove_image('t2') colin.remove_image('pd') names_to_remove = ( 'Fat', 'Muscles', 'Skin and Muscles', 'Skull', 'Fat 2', 'Dura', 'Marrow' ) labels = [colin.NAME_TO_LABEL[name] for name in names_to_remove] skull_stripping = tio.RemoveLabels(labels) only_brain = skull_stripping(label_map) colin.add_image(only_brain, 'brain') colors = { 0: (0, 0, 0), 1: (127, 255, 212), 2: (96, 204, 96), 3: (240, 230, 140), 4: (176, 48, 96), 5: (48, 176, 96), 6: (220, 247, 164), 7: (103, 255, 255), 9: (205, 62, 78), 10: (238, 186, 243), 11: (119, 159, 176), 12: (220, 216, 20), } colin.plot(cmap_dict={'cls': colors, 'brain': colors}) ``` -------------------------------- ### Efficient Patch Pre-fetching with tio.Queue Source: https://context7.com/torchio-project/torchio/llms.txt Use tio.Queue for patch-based training to prefetch subjects with multiple CPU workers, extract patches, shuffle them, and serve batches to the GPU. Ensure num_workers is 0 for the final loader. ```python import torch import torchio as tio subjects = [tio.datasets.Colin27() for _ in range(20)] transform = tio.Compose([ tio.RescaleIntensity(out_min_max=(0, 1)), tio.RandomAffine(p=0.5), ]) dataset = tio.SubjectsDataset(subjects, transform=transform) sampler = tio.UniformSampler(patch_size=96) patches_queue = tio.Queue( subjects_dataset=dataset, max_length=300, # buffer size in number of patches samples_per_volume=10, # patches extracted per subject per epoch sampler=sampler, num_workers=4, # parallel CPU workers shuffle_subjects=True, shuffle_patches=True, ) # num_workers MUST be 0 for the patches loader patches_loader = tio.SubjectsLoader( patches_queue, batch_size=16, num_workers=0, ) model = torch.nn.Identity() for patches_batch in patches_loader: inputs = patches_batch['t1'][tio.DATA] # (16, 1, 96, 96, 96) targets = patches_batch['brain'][tio.DATA] # (16, 1, 96, 96, 96) logits = model(inputs) ``` -------------------------------- ### Run Specific Tests Source: https://github.com/torchio-project/torchio/blob/main/CONTRIBUTING.md Execute a subset of tests by specifying the path to the test file. This is useful for quickly verifying changes in a particular area. ```bash uv run pytest tests/data/test_image.py ``` -------------------------------- ### Run Unit Tests Source: https://github.com/torchio-project/torchio/blob/main/CONTRIBUTING.md Execute the unit tests using pytest to ensure your changes are working correctly. The '-x' flag stops the test run after the first failure. ```bash uv run pytest -x ``` -------------------------------- ### RandomAffineElasticDeformation Usage Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/augmentation/RandomAffineElasticDeformation.md This snippet demonstrates how to initialize and apply the RandomAffineElasticDeformation transform. It shows how to configure the elastic deformation parameters and then use the transform on a sample image. ```APIDOC ## RandomAffineElasticDeformation ### Description Apply random affine and elastic deformation to an image. ### Parameters - **elastic_kwargs** (dict, optional) - Keyword arguments for `RandomElasticDeformation`. Defaults to None. - **p** (float, optional) - Probability of applying the transform. Defaults to 0.5. - **return_transform** (bool, optional) - If True, return the transform applied to the image. Defaults to False. ### Example ```python import torchio as tio # Load a sample subject subject = tio.datasets.Slicer('CTChest') ct = subject.CT_chest # Define parameters for elastic deformation elastic_kwargs = {'max_displacement': (17, 12, 2)} # Initialize the transform transform = tio.RandomAffineElasticDeformation(elastic_kwargs=elastic_kwargs) # Apply the transform to the image ct_transformed = transform(ct) # Add the transformed image to the subject and plot subject.add_image(ct_transformed, 'Transformed') subject.plot() ``` ``` -------------------------------- ### Create and Use SubjectsDataset Source: https://context7.com/torchio-project/torchio/llms.txt Initialize a `SubjectsDataset` with a list of subjects and an optional transform. Use `dry_iter()` to iterate over metadata without loading images. Datasets can be reconstructed from `DataLoader` batches using `from_batch`. ```python import torchio as tio subjects = [ tio.Subject(t1=tio.ScalarImage(f'subject_{i}_t1.nii.gz'), label=tio.LabelMap(f'subject_{i}_seg.nii.gz')) for i in range(100) ] transform = tio.Compose([ tio.ToCanonical(), tio.Resample(1), # 1 mm isotropic tio.CropOrPad((192, 192, 144)), tio.RescaleIntensity(out_min_max=(0, 1)), tio.RandomAffine(p=0.5), tio.RandomNoise(p=0.25), ]) dataset = tio.SubjectsDataset(subjects, transform=transform) print(len(dataset)) # 100 subject_0 = dataset[0] # Iterate metadata without loading images for s in dataset.dry_iter(): print(s.age) # Reconstruct a dataset from a DataLoader batch batch = next(iter(tio.SubjectsLoader(dataset, batch_size=4))) recovered_dataset = tio.SubjectsDataset.from_batch(batch) ``` -------------------------------- ### Inspect Image Metadata with `tiohd` Source: https://github.com/torchio-project/torchio/blob/main/docs/interfaces/cli.md Use `tiohd` to print image metadata to the console. Adding the `--plot` argument will visualize the image using Matplotlib. ```bash $ tiohd ~/.cache/torchio/mni_colin27_1998_nifti/colin27_t1_tal_lin.nii ``` -------------------------------- ### Dense Inference with tio.GridSampler and tio.GridAggregator Source: https://context7.com/torchio-project/torchio/llms.txt Perform dense patch-based inference by exhaustively tiling a volume with GridSampler and collecting predictions with GridAggregator. Configure overlap_mode for handling patch overlaps. ```python import torch import torch.nn as nn import torchio as tio subject = tio.datasets.Colin27() patch_size = (96, 96, 96) patch_overlap = (16, 16, 16) # must be even integers grid_sampler = tio.GridSampler( subject=subject, patch_size=patch_size, patch_overlap=patch_overlap, padding_mode='reflect', # pad borders before sampling ) print(f'Number of patches: {len(grid_sampler)}') patch_loader = tio.SubjectsLoader(grid_sampler, batch_size=4, num_workers=0) aggregator = tio.GridAggregator( grid_sampler, overlap_mode='average', # 'crop', 'average', or 'hann' ) model = nn.Identity().eval() with torch.no_grad(): for patches_batch in patch_loader: input_tensor = patches_batch['t1'][tio.DATA] locations = patches_batch[tio.LOCATION] logits = model(input_tensor) predictions = logits.argmax(dim=tio.CHANNELS_DIMENSION, keepdim=True) aggregator.add_batch(predictions, locations) output_volume = aggregator.get_output_tensor() # shape: (C, W, H, D) print(output_volume.shape) ``` -------------------------------- ### Reproduce Transforms Using History Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/index.md Demonstrates how to reproduce a sequence of applied transforms on a Subject. The get_composed_history() method retrieves the transform history, which can then be reapplied to the original subject. ```python >>> import torchio as tio >>> subject = tio.datasets.FPG() >>> transforms = ( ... tio.CropOrPad((100, 200, 300)), ... tio.RandomFlip(axes=['LR', 'AP', 'IS']), ... tio.OneOf([tio.RandomAnisotropy(), tio.RandomElasticDeformation()]), ... ) >>> transform = tio.Compose(transforms) >>> transformed = transform(subject) >>> reproduce_transform = transformed.get_composed_history() >>> reproduced = reproduce_transform(subject) ``` -------------------------------- ### Integrate MONAI Transforms with MonaiAdapter Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/index.md Illustrates using MONAI dictionary transforms within a TorchIO pipeline by wrapping them with MonaiAdapter. This facilitates interoperability between the two libraries. ```python >>> import torchio as tio >>> from monai.transforms import NormalizeIntensityd, RandSpatialCropd >>> pipeline = tio.Compose([ ... tio.ToCanonical(), ... tio.MonaiAdapter(NormalizeIntensityd(keys=["t1"])), ... tio.RandomFlip(), ... tio.MonaiAdapter( ... RandSpatialCropd(keys=["t1", "seg"], roi_size=[64, 64, 64]), ... ), ... ]) ``` -------------------------------- ### Applying and Inverting Transforms Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/index.md Demonstrates applying a random affine transform to a subject, inferring a segmentation on the transformed data, and then applying the inverse transform to bring the segmentation back to the original space. This is useful for test-time augmentation or aleatoric uncertainty estimation. ```python import torchio as tio # Mock a segmentation CNN def model(x): return x subject = tio.datasets.Colin27() transform = tio.RandomAffine() segmentations = [] num_segmentations = 10 for _ in range(num_segmentations): transform = tio.RandomAffine(image_interpolation='bspline') transformed = transform(subject) segmentation = model(transformed) transformed_native_space = segmentation.apply_inverse_transform(image_interpolation='linear') segmentations.append(transformed_native_space) ``` -------------------------------- ### Simulate MRI ghosting artifacts with tio.RandomGhosting Source: https://context7.com/torchio-project/torchio/llms.txt Apply RandomGhosting to simulate periodic ghosting artifacts by zeroing out k-space lines. Adjust the number of ghosts, axes, intensity, and restore factor. ```python import torchio as tio ghosting = tio.RandomGhosting( num_ghosts=(4, 10), axes=(0, 1, 2), intensity=(0.5, 1), restore=0.02, p=0.3, ) subject = tio.datasets.Colin27() ghosted = ghosting(subject) ``` -------------------------------- ### Apply Transform with `tiotr` Source: https://github.com/torchio-project/torchio/blob/main/docs/interfaces/cli.md Use `tiotr` to apply a transform to an image file from the command line. Specify input and output files, the transform name, and optional keyword arguments for the transform. A random seed can also be set for reproducibility. ```bash $ tiotr input.nii RandomAffine output.nii.gz --kwargs "degrees=(0,0,10) scales=0.1" --seed 42 ``` -------------------------------- ### CropOrPad Source: https://context7.com/torchio-project/torchio/llms.txt `CropOrPad` resizes volumes to a target spatial shape by cropping or padding, typically centered, to standardize input dimensions. ```APIDOC ## `tio.CropOrPad` — Resize volumes to a target shape Crops or pads a volume to a target spatial shape. The crop/pad is centered by default. Useful for standardizing input dimensions across a dataset. ```python import torchio as tio ``` -------------------------------- ### Resizing Volumes with CropOrPad Source: https://context7.com/torchio-project/torchio/llms.txt Resize volumes to a target spatial shape using `tio.CropOrPad`. This transform crops or pads the volume, centered by default, and is useful for standardizing input dimensions. ```python import torchio as tio ``` -------------------------------- ### Transform Reproducibility with Replay and Invert Source: https://context7.com/torchio-project/torchio/llms.txt Record applied transforms in `applied_transforms` to replay them on new data or invert predictions back to the original image space. Useful for test-time augmentation. ```python import torchio as tio subject = tio.datasets.FPG() transform = tio.Compose([ tio.CropOrPad((128, 128, 128)), tio.RandomFlip(axes=['LR', 'AP', 'IS']), tio.RandomAffine(degrees=15, image_interpolation='bspline'), ]) transformed = transform(subject) # Replay exact same transform on new data replay_transform = transformed.get_composed_history() replayed = replay_transform(subject) # Test-time augmentation: augment, infer, invert back to original space def model(x): return x # mock segmentation model segmentations = [] for _ in range(10): aug_transform = tio.RandomAffine(image_interpolation='bspline') augmented = aug_transform(subject) segmentation = model(augmented) # Bring segmentation back to original space in_native_space = segmentation.apply_inverse_transform( image_interpolation='linear' ) segmentations.append(in_native_space) ``` -------------------------------- ### Simulate anisotropic acquisition with tio.RandomAnisotropy Source: https://context7.com/torchio-project/torchio/llms.txt Simulate thick-slice acquisition using RandomAnisotropy by downsampling and upsampling along a random axis. This helps networks become robust to varying slice thicknesses. ```python import torchio as tio anisotropy = tio.RandomAnisotropy( axes=(0, 1, 2), downsampling=(1.5, 5), # downsampling factor range image_interpolation='linear', p=0.25, ) subject = tio.datasets.FPG() degraded = anisotropy(subject) ``` -------------------------------- ### RandomGhosting Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/augmentation/RandomGhosting.md Applies random ghosting artifacts to a 3D image, simulating k-space aliasing. ```APIDOC ## RandomGhosting ### Description Simulates MRI k-space ghosting artifacts by introducing shifted copies of the image. ### Parameters - **num_ghosts** (int, optional): The number of ghost images to generate. Defaults to 1. - **ghost_scale** (tuple of float, optional): The scaling factor for the ghost images. Defaults to (0.05, 0.1). - **ghost_intensity** (tuple of float, optional): The intensity of the ghost images. Defaults to (0.1, 0.2). - **p** (float, optional): Probability of applying the transform. Defaults to 0.5. - **keys** (tuple of str, optional): A sequence of keys to apply the transform to. Defaults to ('image',) ### Example ```python import torch import torchio as tio data = torch.rand(1, 1, 64, 64, 64) subject = tio.Subject({'image': tio.ScalarImage(tensor=data)}) transform = tio.RandomGhosting(num_ghosts=2, ghost_scale=(0.05, 0.15), ghost_intensity=(0.1, 0.3), p=0.7) transformed_subject = transform(subject) ``` ``` -------------------------------- ### Display Image Metadata and Plot with tiohd Source: https://context7.com/torchio-project/torchio/llms.txt Use `tiohd` to view image metadata and simultaneously generate a plot for visualization. This combines inspection with a visual representation of the image properties. ```bash # Print metadata and display with Matplotlib tiohd t1.nii.gz --plot ``` -------------------------------- ### IXI Datasets Source: https://github.com/torchio-project/torchio/blob/main/docs/datasets.md Access the IXI and IXITiny datasets. Please visit the corresponding website for data usage agreements and to acknowledge authors' publications. ```APIDOC ## IXI ::: torchio.datasets.IXI ::: torio.datasets.IXITiny ``` -------------------------------- ### Dense Inference with Grid Sampler and Aggregator Source: https://github.com/torchio-project/torchio/blob/main/docs/patches/inference.md Use GridSampler to divide a 3D image into patches and GridAggregator to combine the inference results. This approach is suitable for large images that do not fit into memory. ```python import torch import torch.nn as nn import torchio as tio patch_overlap = 4, 4, 4 # or just 4 patch_size = 88, 88, 60 subject = tio.datasets.Colin27() print(subject) grid_sampler = tio.inference.GridSampler( subject, patch_size, patch_overlap, ) patch_loader = tio.SubjectsLoader(grid_sampler, batch_size=4) aggregator = tio.inference.GridAggregator(grid_sampler) model = nn.Identity().eval() with torch.no_grad(): for patches_batch in patch_loader: input_tensor = patches_batch['t1'][tio.DATA] locations = patches_batch[tio.LOCATION] logits = model(input_tensor) labels = logits.argmax(dim=tio.CHANNELS_DIMENSION, keepdim=True) outputs = labels aggregator.add_batch(outputs, locations) output_tensor = aggregator.get_output_tensor() ``` -------------------------------- ### Create and Manipulate Subject with TorchIO Source: https://context7.com/torchio-project/torchio/llms.txt Group multiple `Image` instances and metadata for a single subject. Supports attribute access, spatial property checks, dynamic image addition/removal, slicing, and explicit loading/unloading of images. ```python import torchio as tio subject = tio.Subject( t1=tio.ScalarImage('t1.nii.gz'), t2=tio.ScalarImage('t2.nii.gz'), label=tio.LabelMap('seg.nii.gz'), diagnosis='positive', age=45, ) print(subject) # Subject(Keys: ('t1', 't2', 'label', 'diagnosis', 'age'); images: 3) # Attribute access (same as dict access) print(subject.t1.shape) # Spatial properties (require consistent shapes across images) print(subject.spatial_shape) # (W, H, D) print(subject.spacing) # (sx, sy, sz) in mm # Add / remove images dynamically subject.add_image(tio.ScalarImage('flair.nii.gz'), 'flair') subject.remove_image('flair') # Slicing returns a new Subject with sliced images sliced = subject[0, :, 64:128, :] # Check all images share the same space subject.check_consistent_space() # Load / unload all images explicitly subject.load() subject.unload() ``` -------------------------------- ### Kaggle Datasets Source: https://github.com/torchio-project/torchio/blob/main/docs/datasets.md Access Kaggle datasets including RSNAMICCAI and RSNACervicalSpineFracture. Please visit the corresponding website for data usage agreements and to acknowledge authors' publications. ```APIDOC ## Kaggle datasets ::: torchio.datasets.RSNAMICCAI ::: torio.datasets.RSNACervicalSpineFracture ``` -------------------------------- ### Chaining Transforms with Compose Source: https://context7.com/torchio-project/torchio/llms.txt Apply a sequence of transforms in order using `tio.Compose`. The `p` argument in individual transforms controls their application probability. This is analogous to `torchvision.transforms.Compose`. ```python import torchio as tio transform = tio.Compose([ tio.ToCanonical(), tio.Resample(1), tio.CropOrPad((192, 192, 144)), tio.ZNormalization(masking_method=tio.ZNormalization.mean), tio.RandomAffine(scales=0.1, degrees=10, p=0.75), tio.RandomFlip(axes=['LR'], p=0.5), tio.RandomNoise(std=0.05, p=0.25), tio.RandomBiasField(coefficients=0.5, p=0.3), ]) subject = tio.datasets.Colin27() transformed = transform(subject) print(transformed.t1.shape) ``` -------------------------------- ### Compose Source: https://github.com/torchio-project/torchio/blob/main/docs/transforms/augmentation/index.md Compose several transforms together to create a pipeline of augmentations. ```APIDOC ## Compose ### Description Compose several transforms together. ### Usage ```python torch.nn.Sequential( torchio.transforms.RandomFlip(axes=('LR',)), torchio.transforms.RandomAffine(scales=(1, 1.1), degrees=5), ) ``` ``` -------------------------------- ### BibTeX Entry for TorchIO Paper Source: https://github.com/torchio-project/torchio/blob/main/README.md Use this BibTeX entry to cite the TorchIO paper in your academic work. It includes all necessary details for proper attribution. ```bibtex @article{perez-garcia_torchio_2021, title = {{TorchIO}: a {Python} library for efficient loading, preprocessing, augmentation and patch-based sampling of medical images in deep learning}, journal = {Computer Methods and Programs in Biomedicine}, pages = {106236}, year = {2021}, issn = {0169-2607}, doi = {https://doi.org/10.1016/j.cmpb.2021.106236}, url = {https://www.sciencedirect.com/science/article/pii/S0169260721003102}, author = {P{\'e}rez-Garc{\'i}a, Fernando and Sparks, Rachel and Ourselin, S{\'e}bastien}, } ``` -------------------------------- ### Rescaling Intensity with RescaleIntensity Source: https://context7.com/torchio-project/torchio/llms.txt Normalize voxel intensities of scalar images to a target range using `tio.RescaleIntensity`. Optionally use `percentiles` for clipping outliers before rescaling. Can be applied selectively using `include`. ```python import torchio as tio # Rescale to [0, 1] clipping at 1st and 99th percentiles rescale = tio.RescaleIntensity( out_min_max=(0, 1), percentiles=(1, 99), # clip outliers before rescaling ) subject = tio.datasets.Colin27() rescaled = rescale(subject) print(rescaled.t1.data.min(), rescaled.t1.data.max()) # ~0.0, ~1.0 # Apply only to specific images rescale_selective = tio.RescaleIntensity( out_min_max=(-1, 1), include=['t1'], ) ``` -------------------------------- ### Load Label Map with TorchIO Source: https://context7.com/torchio-project/torchio/llms.txt Load a segmentation mask as a `LabelMap`. Spatial transforms use nearest-neighbor interpolation to preserve categorical values. Supports loading from file paths or PyTorch tensors. ```python import torchio as tio seg = tio.LabelMap('brain_seg.nii.gz') print(seg[tio.TYPE]) # 'label' # From tensor import torch labels = torch.zeros(1, 128, 128, 64, dtype=torch.int16) labels[0, 40:80, 40:80, 20:40] = 1 # region of interest seg_from_tensor = tio.LabelMap(tensor=labels) # Slice a subvolume (updates affine origin automatically) sub_seg = seg[0, :, 64:128, :] print(sub_seg.shape) ```