SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2003.04696 · 2020

TorchIO: A Python library for efficient loading, preprocessing, augmentation and patch-based sampling of medical images in deep learning

arXiv · PDF · Open in the Atlas

Code that ran

6 of 6 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 6 have no contract verdict; 0 failures of our instrument; 0 no recorded run), measured 2026-11-21; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2003.04696.json · badge: /api/ran/2003.04696.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
DiamondLightSource/gas-hydrate-segmentation-unets community (classifier label)
classifier basis not recorded on the link
3 ran · 0 no recorded run
MitraDP/Pancreas-CT-image-and-volumetric-segmentation community (classifier label)
classifier basis not recorded on the link
3 ran · 0 no recorded run
FunctionStatusWhere it lives
CheckExt Ran
ran on a synthesized input
DiamondLightSource/gas-hydrate-segmentation-unets/unet_methods/unet_2d/utilities/cmdline.py
code served (permissive licence) · get_code("60b0812fdd32621c")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned type. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import argparse
import os.path

def CheckExt(choices):
    """Wrapper to return the class
    """

    class Act(argparse.Action):
        """Class to allow checking of filename extensions in argparse. Taken
        from https://stackoverflow.com/questions/15203829/python-argparse-file-extension-checking
        """

        def __call__(self, parser, namespace, fname, option_string=None):
            ext = os.path.splitext(fname)[1][1:]
            if ext not in choices:
                option_string = '({})'.format(option_string) if option_string else ''
                parser.error("Wrong filetype: file doesn't end with {}{}".format(choices, option_string))
            else:
                setattr(namespace, self.dest, fname)
    return Act


# Setup code to construct valid arguments
ARGS = {
    "choices": ["txt", "csv", "json"]
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type type — a type output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a type output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
numpy_from_hdf5 Ran
ran on a synthesized input
DiamondLightSource/gas-hydrate-segmentation-unets/unet_methods/unet_3d/train_3d_unet.py
code served (permissive licence) · get_code("f4b600ad05fe339a")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned ndarray, ndim 2, dtype family float, shape (4, 3) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import tempfile
import h5py as h5
import numpy as np
import pathlib

# Create a temporary HDF5 file with test data
temp_dir = tempfile.mkdtemp()
temp_path = pathlib.Path(temp_dir) / "test_data.h5"

# Create an HDF5 file with standard data path
with h5.File(temp_path, 'w') as f:
    test_data = np.random.rand(4, 3).astype(np.float32)
    f.create_dataset('/data', data=test_data)

# Also create a NeXus-style file for testing nexus=True
temp_path_nexus = pathlib.Path(temp_dir) / "test_nexus.h5"
with h5.File(temp_path_nexus, 'w') as f:
    test_data_nexus = np.random.rand(5, 6).astype(np.float32)
    f.create_dataset('processed/result/data', data=test_data_nexus)

ARGS = {
    'path': temp_path,
    'hdf5_path': '/data',
    'nexus': False,
    'lazy': False
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
h5py, numpy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type ndarray, ndim 2, dtype family float, shape (4, 3) — shape (4, 3) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
partitioning Ran
ran on a synthesized input
MitraDP/Pancreas-CT-image-and-volumetric-segmentation/dataset.py
code served (permissive licence) · get_code("3933907a7e1c3e37")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned dict. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import random

# Construct arguments for the partitioning function
patients_list = [
    {'id': 1, 'name': 'Patient_A'},
    {'id': 2, 'name': 'Patient_B'},
    {'id': 3, 'name': 'Patient_C'},
    {'id': 4, 'name': 'Patient_D'},
    {'id': 5, 'name': 'Patient_E'},
    {'id': 6, 'name': 'Patient_F'},
    {'id': 7, 'name': 'Patient_G'},
    {'id': 8, 'name': 'Patient_H'},
    {'id': 9, 'name': 'Patient_I'},
    {'id': 10, 'name': 'Patient_J'},
]

split_ratio = (0.6, 0.2)

ARGS = {
    'patients_list': patients_list,
    'split_ratio': split_ratio,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
patch_creator Ran
ran on a synthesized input
MitraDP/Pancreas-CT-image-and-volumetric-segmentation/volume_patch_composer.py
code served (permissive licence) · get_code("27d84b3c44f94eef")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned tuple, ndim 5, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import os
import tempfile
import shutil

torch.manual_seed(0)

# Create a temporary directory structure to simulate /content/data3D
temp_dir = tempfile.mkdtemp()
data3d_dir = os.path.join(temp_dir, 'content', 'data3D')
os.makedirs(data3d_dir, exist_ok=True)

# Create mock CT and Mask tensors and save them
# CT tensor: shape (1, 1, 8, 8, 8) - will be squeezed to (8, 8, 8)
# Mask tensor: shape (1, 1, 8, 8, 8) - will be squeezed to (8, 8, 8)
ct_tensor = torch.randn(1, 1, 8, 8, 8)
mask_tensor = torch.randint(0, 2, (1, 1, 8, 8, 8)).float()

# Save for sample_1
torch.save(ct_tensor, os.path.join(data3d_dir, 'sample_1_CT.pt'))
torch.save(mask_tensor, os.path.join(data3d_dir, 'sample_1_Mask.pt'))

# Save for sample_2
torch.save(ct_tensor, os.path.join(data3d_dir, 'sample_2_CT.pt'))
torch.save(mask_tensor, os.path.join(data3d_dir, 'sample_2_Mask.pt'))

# Patch the path to use our temp directory
original_join = os.path.join
def patched_join(*args, **kwargs):
    result = original_join(*args, **kwargs)
    if '/content/data3D' in result:
        result = result.replace('/content/data3D', data3d_dir)
    return result
os.path.join = patched_join

ARGS = {
    'partition': ['sample_1', 'sample_2'],
    'kw': 3,
    'kh': 4,
    'kc': 5,
    'dw': 2,
    'dh': 2,
    'dc': 2
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple, ndim 5, dtype family float — a tuple output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
tensor_from_hdf5 Ran
ran on a synthesized input
DiamondLightSource/gas-hydrate-segmentation-unets/unet_methods/unet_3d/predict_3d_unet.py
code served (permissive licence) · get_code("fba4dbf1f3885826")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned Tensor, ndim 2, dtype family float, shape (2, 4) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import h5py as h5
import torch
import tempfile
import os
import numpy as np

torch.manual_seed(0)

# Create a temporary HDF5 file with sample data
temp_dir = tempfile.mkdtemp()
file_path = os.path.join(temp_dir, "test_data.h5")

# Create sample data and write to HDF5
sample_data = np.random.randn(2, 4).astype(np.float32)

with h5.File(file_path, 'w') as f:
    f.create_dataset('tensor_data', data=sample_data)

# Define arguments
ARGS = {
    'file_path': file_path,
    'data_path': 'tensor_data'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
h5py, numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 2, dtype family float, shape (2, 4) — shape (2, 4) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
volume Ran
ran on a synthesized input
MitraDP/Pancreas-CT-image-and-volumetric-segmentation/inference.py
code served (permissive licence) · get_code("7c421199d69ae59b")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned tuple, ndim 4, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import numpy as np

# Create small sample data structures for the function
num_patch_width = 2
num_patch_height = 3
num_patch_depth = 2
num_batches = 2
r = 1
kc = 2

# Each element in CT_subvol[q] should be a 3D array with shape (depth, height, width)
# After squeeze and transpose(0, 2, 1), it becomes (depth, width, height)
# We need to create patches that when indexed by k give us 2D slices

# Create CT_subvol: list of batches, each batch contains patches
CT_subvol = []
for batch_idx in range(num_batches):
    batch_patches = []
    # We need num_patch_width * num_patch_height patches per batch
    # Each patch should have shape that after squeeze and transpose gives (kc, patch_h, patch_w)
    for patch_idx in range(num_patch_width * num_patch_height * num_patch_depth):
        # Create patch with shape (kc, patch_h, patch_w, 1) so squeeze works
        patch = np.random.rand(kc, 4, 5, 1)
        batch_patches.append(patch)
    CT_subvol.append(batch_patches)

# Create mask_subvol with same structure
mask_subvol = []
for batch_idx in range(num_batches):
    batch_patches = []
    for patch_idx in range(num_patch_width * num_patch_height * num_patch_depth):
        patch = np.random.rand(kc, 4, 5, 1)
        batch_patches.append(patch)
    mask_subvol.append(batch_patches)

# Create predict_subvol with same structure (no squeeze needed based on code)
predict_subvol = []
for batch_idx in range(num_batches):
    batch_patches = []
    for patch_idx in range(num_patch_width * num_patch_height * num_patch_depth):
        patch = np.random.rand(kc, 4, 5)
        batch_patches.append(patch)
    predict_subvol.append(batch_patches)

ARGS = {
    "num_patch_width": num_patch_width,
    "num_patch_height": num_patch_height,
    "num_patch_depth": num_patch_depth,
    "num_batches": num_batches,
    "r": r,
    "CT_subvol": CT_subvol,
    "mask_subvol": mask_subvol,
    "predict_subvol": predict_subvol,
    "kc": kc,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple, ndim 4, dtype family float — a tuple output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block

Also present in other papers' code

Of 6 samples lifted from this paper's linked repositories, 6 carry a function identity and 0 do not. Of the 6 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 0 later) and 6 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-21.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Processing of medical images such as MRI or CT presents unique challenges compared to RGB images typically used in computer vision. These include a lack of labels for large datasets, high computational costs, and metadata to describe the physical properties of voxels. Data augmentation is used to artificially increase the size of the training datasets. Training with image patches decreases the need for computational power. Spatial metadata needs to be carefully taken into account in order to ensure a correct alignment of volumes. We present TorchIO, an open-source Python library to enable efficient loading, preprocessing, augmentation and patch-based sampling of medical images for deep learning. TorchIO follows the style of PyTorch and integrates standard medical image processing libraries to efficiently process images during training of neural networks. TorchIO transforms can be composed, reproduced, traced and extended. We provide multiple generic preprocessing and augmentation operations as well as simulation of MRI-specific artifacts. Source code, comprehensive tutorials and extensive documentation for TorchIO can be found at https://torchio.rtfd.io/. The package can be installed from the Python Package Index running 'pip install torchio'. It includes a command-line interface which allows users to apply transforms to image files without using Python. Additionally, we provide a graphical interface within a TorchIO extension in 3D Slicer to visualize the effects of transforms. TorchIO was developed to help researchers standardize medical image processing pipelines and allow them to focus on the deep learning experiments. It encourages open science, as it supports reproducibility and is version controlled so that the software can be cited precisely. Due to its modularity, the library is compatible with other frameworks for deep learning with medical images.

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2003.04696")
get_code_for_paper("2003.04696")
have("2003.04696")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2003.04696.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2003.04696.svg)](https://syntology.ai/paper/2003.04696)

Connect an agent — have() is free.