Skip to content

Image

ScalarImage

Bases: Image

Image with scalar (intensity) data.

Transforms use isinstance(image, ScalarImage) to identify intensity images for operations like normalization or augmentation.

Examples:

>>> import torchio as tio
>>> image = tio.ScalarImage("t1.nii.gz")
>>> image = tio.ScalarImage(torch.randn(1, 256, 256, 176))
Source code in src/torchio/data/image.py
class ScalarImage(Image):
    """Image with scalar (intensity) data.

    Transforms use `isinstance(image, ScalarImage)` to identify intensity
    images for operations like normalization or augmentation.

    Examples:
        >>> import torchio as tio
        >>> image = tio.ScalarImage("t1.nii.gz")
        >>> image = tio.ScalarImage(torch.randn(1, 256, 256, 176))
    """

path property

Path to the image file, if any.

is_loaded property

Whether the image data is loaded into memory.

data property

Tensor data with shape (C, I, J, K). Triggers lazy load if needed.

affine property

4x4 affine matrix mapping voxel indices to world coordinates.

metadata property

Arbitrary metadata dict.

dataobj property

Lazy data backend for advanced operations like slicing.

Returns the underlying backend without materializing the full tensor. For NIfTI files this is a NibabelBackend; for NIfTI-Zarr files a ZarrBackend; for in-memory images a TensorBackend.

shape property

Tensor shape as (C, I, J, K).

spatial_shape property

Spatial dimensions as (I, J, K).

num_channels property

Number of channels.

spacing property

Voxel spacing in mm, derived from the affine.

origin property

Center of the first voxel in world coordinates.

memory property

Number of bytes the tensor would occupy in RAM.

dtype property

Data type of the image.

Returns the PyTorch dtype if the image is loaded, otherwise reads the on-disk dtype from the header without loading data.

orientation property

Orientation codes from the affine.

points property

Named sets of points attached to this image.

bounding_boxes property

Named sets of bounding boxes attached to this image.

device property

Device the image data resides on.

get_inverse_transform(*, warn=True, ignore_intensity=False)

Get a composed transform that inverts the applied history.

Returns a Compose of the inverse of each applied transform, in reverse order. Non-invertible transforms are skipped (with a warning if warn=True).

Parameters:

Name Type Description Default
warn bool

Issue a warning for non-invertible transforms.

True
ignore_intensity bool

Skip all intensity transforms.

False

Returns:

Type Description
Any

A Compose transform that undoes the history.

Source code in src/torchio/data/invertible.py
def get_inverse_transform(
    self,
    *,
    warn: bool = True,
    ignore_intensity: bool = False,
) -> Any:
    """Get a composed transform that inverts the applied history.

    Returns a [`Compose`][torchio.Compose] of the inverse of each
    applied transform, in reverse order. Non-invertible transforms
    are skipped (with a warning if `warn=True`).

    Args:
        warn: Issue a warning for non-invertible transforms.
        ignore_intensity: Skip all intensity transforms.

    Returns:
        A `Compose` transform that undoes the history.
    """
    from ..transforms.inverse import get_inverse_transform

    return get_inverse_transform(
        self.applied_transforms,
        warn=warn,
        ignore_intensity=ignore_intensity,
    )

apply_inverse_transform(**kwargs)

Apply the inverse of all applied transforms, in reverse order.

Non-invertible transforms are skipped. Intensity transforms can be ignored with ignore_intensity=True.

Parameters:

Name Type Description Default
**kwargs Any

Forwarded to get_inverse_transform() (warn, ignore_intensity).

{}

Returns:

Type Description
Self

Data with transforms undone.

Examples:

>>> transformed = transform(subject)
>>> restored = transformed.apply_inverse_transform()
Source code in src/torchio/data/invertible.py
def apply_inverse_transform(self, **kwargs: Any) -> Self:
    """Apply the inverse of all applied transforms, in reverse order.

    Non-invertible transforms are skipped. Intensity transforms
    can be ignored with `ignore_intensity=True`.

    Args:
        **kwargs: Forwarded to
            `get_inverse_transform()` (`warn`,
            `ignore_intensity`).

    Returns:
        Data with transforms undone.

    Examples:
        >>> transformed = transform(subject)
        >>> restored = transformed.apply_inverse_transform()
    """
    inverse_transform = self.get_inverse_transform(**kwargs)
    result = inverse_transform(self)
    if hasattr(result, "applied_transforms"):
        result.applied_transforms = []
    return result

clear_history()

Remove all applied transform records.

Source code in src/torchio/data/invertible.py
def clear_history(self) -> None:
    """Remove all applied transform records."""
    self.applied_transforms = []

load()

Load data from disk into memory.

Source code in src/torchio/data/image.py
def load(self) -> None:
    """Load data from disk into memory."""
    if self._data is not None:
        return
    if self._try_load_via_backend():
        return
    if self._path is None:
        msg = "Cannot load: no path or backend set"
        raise RuntimeError(msg)
    tensor, affine_array = self._reader(self._path, **self._reader_kwargs)
    self._data = tensor
    if self._affine is None:
        self._affine = AffineMatrix(affine_array)
    self._apply_channels_last()

set_data(tensor)

Replace the image data with a new tensor.

The lazy backend is refreshed so that dataobj, dtype, and shape stay coherent with the new tensor. The affine is preserved when one is set or can be read from the source header; for an image created without any source (e.g. ScalarImage() then set_data) it defaults to the identity affine.

Parameters:

Name Type Description Default
tensor TypeImageData | ndarray

4D tensor with shape (C, I, J, K).

required
Source code in src/torchio/data/image.py
def set_data(self, tensor: TypeImageData | np.ndarray) -> None:
    """Replace the image data with a new tensor.

    The lazy backend is refreshed so that `dataobj`, `dtype`, and
    `shape` stay coherent with the new tensor. The affine is preserved when
    one is set or can be read from the source header; for an image created
    without any source (e.g. `ScalarImage()` then `set_data`) it defaults to
    the identity affine.

    Args:
        tensor: 4D tensor with shape (C, I, J, K).
    """
    self._data = self._parse_tensor(tensor)
    self._refresh_backend_from_data()

to(*args, **kwargs)

Move image data and affine to a device and/or cast to a dtype.

Accepts the same arguments as torch.Tensor.to().

Returns:

Type Description
Self

self (modified in-place).

Source code in src/torchio/data/image.py
def to(self, *args: Any, **kwargs: Any) -> Self:
    """Move image data and affine to a device and/or cast to a dtype.

    Accepts the same arguments as `torch.Tensor.to()`.

    Returns:
        `self` (modified in-place).
    """
    self._data = self.data.to(*args, **kwargs)
    if self._affine is not None:
        self._affine.to(*args, **kwargs)
    self._refresh_backend_from_data()
    return self

numpy()

Return the image data as a NumPy array.

If the data is not loaded, reads it from disk first. The returned array shares memory with the tensor if possible (i.e., if the tensor is on CPU and not a view).

Returns:

Type Description
ndarray

4D array with shape (C, I, J, K).

Source code in src/torchio/data/image.py
def numpy(self) -> np.ndarray:
    """Return the image data as a NumPy array.

    If the data is not loaded, reads it from disk first. The returned
    array shares memory with the tensor if possible (i.e., if the
    tensor is on CPU and not a view).

    Returns:
        4D array with shape (C, I, J, K).
    """
    return self.data.cpu().numpy()

new_like(*, data, affine=None)

Create a new image of the same class with new data.

Preserves metadata, annotations, and affine. Uses the existing affine unless a new one is provided. Works correctly with custom subclasses.

Parameters:

Name Type Description Default
data TypeImageData

New 4D torch.Tensor with shape \((C, I, J, K)\).

required
affine AffineMatrix | ArrayLike | None

New \(4 \times 4\) affine. If None, uses self.affine.

None
Source code in src/torchio/data/image.py
def new_like(
    self,
    *,
    data: TypeImageData,
    affine: AffineMatrix | npt.ArrayLike | None = None,
) -> Self:
    r"""Create a new image of the same class with new data.

    Preserves metadata, annotations, and affine. Uses the existing
    affine unless a new one is provided. Works correctly with custom
    subclasses.

    Args:
        data: New 4D [`torch.Tensor`][torch.Tensor] with shape
            $(C, I, J, K)$.
        affine: New $4 \times 4$ affine. If `None`, uses `self.affine`.
    """
    new_affine = (
        self._parse_affine(affine) if affine is not None else self.affine.clone()
    )
    points_copy, bboxes_copy = self._deep_copy_annotations()
    return type(self)(
        data,
        affine=new_affine,
        points=points_copy,
        bounding_boxes=bboxes_copy,
        **dict(self._metadata),
    )

save(path, **kwargs)

Save the image to a file.

NIfTI-Zarr (.nii.zarr) files are written via niizarr (requires the zarr extra). All other formats are written with SimpleITK.

Parameters:

Name Type Description Default
path str | Path

Output file path. The format is inferred from the extension.

required
**kwargs Any

Extra keyword arguments forwarded to the writer. For SimpleITK formats these are passed to SimpleITK.WriteImage().

{}
Source code in src/torchio/data/image.py
def save(
    self,
    path: str | Path,
    **kwargs: Any,
) -> None:
    """Save the image to a file.

    NIfTI-Zarr (`.nii.zarr`) files are written via `niizarr`
    (requires the `zarr` extra). All other formats are written
    with [SimpleITK](https://simpleitk.org/).

    Args:
        path: Output file path. The format is inferred from the
            extension.
        **kwargs: Extra keyword arguments forwarded to the
            writer. For SimpleITK formats these are passed to
            `SimpleITK.WriteImage()`.
    """
    path = Path(path)
    if is_nifti_zarr(path):
        self._save_nii_zarr(path)
    else:
        self._save_sitk(path, **kwargs)

plot(**kwargs)

Plot 3 orthogonal slices of the image.

Requires the [plot] extras (pip install torchio[plot]). See plot_image for the full list of keyword arguments.

Source code in src/torchio/data/image.py
def plot(self, **kwargs: Any) -> Any:
    """Plot 3 orthogonal slices of the image.

    Requires the `[plot]` extras (`pip install torchio[plot]`).
    See [`plot_image`][torchio.visualization.plot_image] for the
    full list of keyword arguments.
    """
    from ..visualization import plot_image

    return plot_image(self, **kwargs)

plot_interactive(*, height=300)

Show an interactive NiiVue viewer in Jupyter.

Requires ipyniivue (pip install torchio[niivue]).

The widget supports scrolling through slices, zooming, and crosshair navigation. Left hemisphere is displayed on the right side of the screen (radiological convention).

Parameters:

Name Type Description Default
height int

Height of the viewer in pixels.

300

Returns:

Type Description
Any

An ipyniivue.NiiVue widget.

Raises:

Type Description
ImportError

If ipyniivue is not installed.

Source code in src/torchio/data/image.py
def plot_interactive(self, *, height: int = 300) -> Any:
    """Show an interactive NiiVue viewer in Jupyter.

    Requires `ipyniivue` (`pip install torchio[niivue]`).

    The widget supports scrolling through slices, zooming, and
    crosshair navigation.  Left hemisphere is displayed on the
    right side of the screen (radiological convention).

    Args:
        height: Height of the viewer in pixels.

    Returns:
        An `ipyniivue.NiiVue` widget.

    Raises:
        ImportError: If `ipyniivue` is not installed.
    """
    import tempfile

    import nibabel as nib
    import numpy as np

    from ..external.imports import get_ipyniivue

    nv = get_ipyniivue()

    data = self.data.cpu().float().numpy()
    if data.ndim == 4 and data.shape[0] == 1:
        data = data[0]
    affine = np.asarray(self.affine.data, dtype=np.float64)
    nii = nib.Nifti1Image(data, affine)
    with tempfile.NamedTemporaryFile(suffix=".nii.gz", delete=False) as f:
        nib.save(nii, f.name)
        path = f.name

    widget = nv.NiiVue(height=height)
    widget.opts.is_radiological_convention = True
    widget.add_volume(nv.Volume(path=path))
    return widget

to_gif(output_path=None, *, seconds=5.0, direction='I', loop=0, rescale=True, optimize=True, reverse=False)

Save an animated GIF sweeping through slices.

Requires Pillow (pip install torchio[plot]).

When output_path is None and the code is running inside a Jupyter notebook, the GIF is written to a temporary file and returned as an IPython.display.Image for inline display. Outside Jupyter, output_path is required.

Parameters:

Name Type Description Default
output_path str | Path | None

Path to the output .gif file. None to auto-create a temporary file (Jupyter only).

None
seconds float

Duration of the full animation in seconds.

5.0
direction str

Anatomical sweep direction ("I", "S", "A", "P", "R", or "L").

'I'
loop int

Number of loops (0 = infinite).

0
rescale bool

Rescale intensities to [0, 255].

True
optimize bool

Attempt to compress the GIF palette.

True
reverse bool

Reverse the temporal order of frames.

False

Returns:

Type Description
Any

IPython.display.Image when running in Jupyter,

Any

None otherwise.

Raises:

Type Description
ValueError

If output_path is None and the code is not running inside a Jupyter notebook.

Source code in src/torchio/data/image.py
def to_gif(
    self,
    output_path: str | Path | None = None,
    *,
    seconds: float = 5.0,
    direction: str = "I",
    loop: int = 0,
    rescale: bool = True,
    optimize: bool = True,
    reverse: bool = False,
) -> Any:
    """Save an animated GIF sweeping through slices.

    Requires `Pillow` (`pip install torchio[plot]`).

    When *output_path* is `None` and the code is running inside
    a Jupyter notebook, the GIF is written to a temporary file and
    returned as an `IPython.display.Image` for inline display.
    Outside Jupyter, *output_path* is required.

    Args:
        output_path: Path to the output `.gif` file.  `None`
            to auto-create a temporary file (Jupyter only).
        seconds: Duration of the full animation in seconds.
        direction: Anatomical sweep direction (`"I"`, `"S"`,
            `"A"`, `"P"`, `"R"`, or `"L"`).
        loop: Number of loops (0 = infinite).
        rescale: Rescale intensities to `[0, 255]`.
        optimize: Attempt to compress the GIF palette.
        reverse: Reverse the temporal order of frames.

    Returns:
        `IPython.display.Image` when running in Jupyter,
        `None` otherwise.

    Raises:
        ValueError: If *output_path* is `None` and the code is
            not running inside a Jupyter notebook.
    """
    output_path = _resolve_media_path(output_path, suffix=".gif")
    from ..visualization import make_gif

    make_gif(
        self,
        output_path,
        seconds=seconds,
        direction=direction,
        loop=loop,
        rescale=rescale,
        optimize=optimize,
        reverse=reverse,
    )
    if _in_jupyter():
        from IPython.display import Image as IPyImage

        return IPyImage(filename=str(output_path))
    return None

to_video(output_path=None, *, seconds=5.0, direction='I', verbosity='error')

Create an MP4 video sweeping through slices.

Requires ffmpeg-python (pip install torchio[video]).

When output_path is None and the code is running inside a Jupyter notebook, the video is written to a temporary file and returned as an IPython.display.Video for inline display. Outside Jupyter, output_path is required.

Parameters:

Name Type Description Default
output_path str | Path | None

Path to the output .mp4 file. None to auto-create a temporary file (Jupyter only).

None
seconds float

Duration of the full video in seconds.

5.0
direction str

Anatomical sweep direction ("I", "S", "A", "P", "R", or "L").

'I'
verbosity str

ffmpeg log level.

'error'

Returns:

Type Description
Any

IPython.display.Video when running in Jupyter,

Any

None otherwise.

Raises:

Type Description
ValueError

If output_path is None and the code is not running inside a Jupyter notebook.

Source code in src/torchio/data/image.py
def to_video(
    self,
    output_path: str | Path | None = None,
    *,
    seconds: float = 5.0,
    direction: str = "I",
    verbosity: str = "error",
) -> Any:
    """Create an MP4 video sweeping through slices.

    Requires `ffmpeg-python` (`pip install torchio[video]`).

    When *output_path* is `None` and the code is running inside
    a Jupyter notebook, the video is written to a temporary file
    and returned as an `IPython.display.Video` for inline
    display.  Outside Jupyter, *output_path* is required.

    Args:
        output_path: Path to the output `.mp4` file.  `None`
            to auto-create a temporary file (Jupyter only).
        seconds: Duration of the full video in seconds.
        direction: Anatomical sweep direction (`"I"`, `"S"`,
            `"A"`, `"P"`, `"R"`, or `"L"`).
        verbosity: ffmpeg log level.

    Returns:
        `IPython.display.Video` when running in Jupyter,
        `None` otherwise.

    Raises:
        ValueError: If *output_path* is `None` and the code is
            not running inside a Jupyter notebook.
    """
    output_path = _resolve_media_path(output_path, suffix=".mp4")
    from ..visualization import make_video

    make_video(
        self,
        output_path,
        seconds=seconds,
        direction=direction,
        verbosity=verbosity,
    )
    if _in_jupyter():
        from IPython.display import Video

        return Video(
            str(output_path),
            embed=True,
            html_attributes="controls autoplay loop muted",
        )
    return None

LabelMap

Bases: Image

Image with label (segmentation) data.

Transforms use isinstance(image, LabelMap) to apply nearest-neighbor interpolation during spatial transforms.

Examples:

>>> import torchio as tio
>>> label = tio.LabelMap("seg.nii.gz")
>>> label = tio.LabelMap(torch.randint(0, 5, (1, 256, 256, 176)))
Source code in src/torchio/data/image.py
class LabelMap(Image):
    """Image with label (segmentation) data.

    Transforms use `isinstance(image, LabelMap)` to apply nearest-neighbor
    interpolation during spatial transforms.

    Examples:
        >>> import torchio as tio
        >>> label = tio.LabelMap("seg.nii.gz")
        >>> label = tio.LabelMap(torch.randint(0, 5, (1, 256, 256, 176)))
    """

path property

Path to the image file, if any.

is_loaded property

Whether the image data is loaded into memory.

data property

Tensor data with shape (C, I, J, K). Triggers lazy load if needed.

affine property

4x4 affine matrix mapping voxel indices to world coordinates.

metadata property

Arbitrary metadata dict.

dataobj property

Lazy data backend for advanced operations like slicing.

Returns the underlying backend without materializing the full tensor. For NIfTI files this is a NibabelBackend; for NIfTI-Zarr files a ZarrBackend; for in-memory images a TensorBackend.

shape property

Tensor shape as (C, I, J, K).

spatial_shape property

Spatial dimensions as (I, J, K).

num_channels property

Number of channels.

spacing property

Voxel spacing in mm, derived from the affine.

origin property

Center of the first voxel in world coordinates.

memory property

Number of bytes the tensor would occupy in RAM.

dtype property

Data type of the image.

Returns the PyTorch dtype if the image is loaded, otherwise reads the on-disk dtype from the header without loading data.

orientation property

Orientation codes from the affine.

points property

Named sets of points attached to this image.

bounding_boxes property

Named sets of bounding boxes attached to this image.

device property

Device the image data resides on.

get_inverse_transform(*, warn=True, ignore_intensity=False)

Get a composed transform that inverts the applied history.

Returns a Compose of the inverse of each applied transform, in reverse order. Non-invertible transforms are skipped (with a warning if warn=True).

Parameters:

Name Type Description Default
warn bool

Issue a warning for non-invertible transforms.

True
ignore_intensity bool

Skip all intensity transforms.

False

Returns:

Type Description
Any

A Compose transform that undoes the history.

Source code in src/torchio/data/invertible.py
def get_inverse_transform(
    self,
    *,
    warn: bool = True,
    ignore_intensity: bool = False,
) -> Any:
    """Get a composed transform that inverts the applied history.

    Returns a [`Compose`][torchio.Compose] of the inverse of each
    applied transform, in reverse order. Non-invertible transforms
    are skipped (with a warning if `warn=True`).

    Args:
        warn: Issue a warning for non-invertible transforms.
        ignore_intensity: Skip all intensity transforms.

    Returns:
        A `Compose` transform that undoes the history.
    """
    from ..transforms.inverse import get_inverse_transform

    return get_inverse_transform(
        self.applied_transforms,
        warn=warn,
        ignore_intensity=ignore_intensity,
    )

apply_inverse_transform(**kwargs)

Apply the inverse of all applied transforms, in reverse order.

Non-invertible transforms are skipped. Intensity transforms can be ignored with ignore_intensity=True.

Parameters:

Name Type Description Default
**kwargs Any

Forwarded to get_inverse_transform() (warn, ignore_intensity).

{}

Returns:

Type Description
Self

Data with transforms undone.

Examples:

>>> transformed = transform(subject)
>>> restored = transformed.apply_inverse_transform()
Source code in src/torchio/data/invertible.py
def apply_inverse_transform(self, **kwargs: Any) -> Self:
    """Apply the inverse of all applied transforms, in reverse order.

    Non-invertible transforms are skipped. Intensity transforms
    can be ignored with `ignore_intensity=True`.

    Args:
        **kwargs: Forwarded to
            `get_inverse_transform()` (`warn`,
            `ignore_intensity`).

    Returns:
        Data with transforms undone.

    Examples:
        >>> transformed = transform(subject)
        >>> restored = transformed.apply_inverse_transform()
    """
    inverse_transform = self.get_inverse_transform(**kwargs)
    result = inverse_transform(self)
    if hasattr(result, "applied_transforms"):
        result.applied_transforms = []
    return result

clear_history()

Remove all applied transform records.

Source code in src/torchio/data/invertible.py
def clear_history(self) -> None:
    """Remove all applied transform records."""
    self.applied_transforms = []

load()

Load data from disk into memory.

Source code in src/torchio/data/image.py
def load(self) -> None:
    """Load data from disk into memory."""
    if self._data is not None:
        return
    if self._try_load_via_backend():
        return
    if self._path is None:
        msg = "Cannot load: no path or backend set"
        raise RuntimeError(msg)
    tensor, affine_array = self._reader(self._path, **self._reader_kwargs)
    self._data = tensor
    if self._affine is None:
        self._affine = AffineMatrix(affine_array)
    self._apply_channels_last()

set_data(tensor)

Replace the image data with a new tensor.

The lazy backend is refreshed so that dataobj, dtype, and shape stay coherent with the new tensor. The affine is preserved when one is set or can be read from the source header; for an image created without any source (e.g. ScalarImage() then set_data) it defaults to the identity affine.

Parameters:

Name Type Description Default
tensor TypeImageData | ndarray

4D tensor with shape (C, I, J, K).

required
Source code in src/torchio/data/image.py
def set_data(self, tensor: TypeImageData | np.ndarray) -> None:
    """Replace the image data with a new tensor.

    The lazy backend is refreshed so that `dataobj`, `dtype`, and
    `shape` stay coherent with the new tensor. The affine is preserved when
    one is set or can be read from the source header; for an image created
    without any source (e.g. `ScalarImage()` then `set_data`) it defaults to
    the identity affine.

    Args:
        tensor: 4D tensor with shape (C, I, J, K).
    """
    self._data = self._parse_tensor(tensor)
    self._refresh_backend_from_data()

to(*args, **kwargs)

Move image data and affine to a device and/or cast to a dtype.

Accepts the same arguments as torch.Tensor.to().

Returns:

Type Description
Self

self (modified in-place).

Source code in src/torchio/data/image.py
def to(self, *args: Any, **kwargs: Any) -> Self:
    """Move image data and affine to a device and/or cast to a dtype.

    Accepts the same arguments as `torch.Tensor.to()`.

    Returns:
        `self` (modified in-place).
    """
    self._data = self.data.to(*args, **kwargs)
    if self._affine is not None:
        self._affine.to(*args, **kwargs)
    self._refresh_backend_from_data()
    return self

numpy()

Return the image data as a NumPy array.

If the data is not loaded, reads it from disk first. The returned array shares memory with the tensor if possible (i.e., if the tensor is on CPU and not a view).

Returns:

Type Description
ndarray

4D array with shape (C, I, J, K).

Source code in src/torchio/data/image.py
def numpy(self) -> np.ndarray:
    """Return the image data as a NumPy array.

    If the data is not loaded, reads it from disk first. The returned
    array shares memory with the tensor if possible (i.e., if the
    tensor is on CPU and not a view).

    Returns:
        4D array with shape (C, I, J, K).
    """
    return self.data.cpu().numpy()

new_like(*, data, affine=None)

Create a new image of the same class with new data.

Preserves metadata, annotations, and affine. Uses the existing affine unless a new one is provided. Works correctly with custom subclasses.

Parameters:

Name Type Description Default
data TypeImageData

New 4D torch.Tensor with shape \((C, I, J, K)\).

required
affine AffineMatrix | ArrayLike | None

New \(4 \times 4\) affine. If None, uses self.affine.

None
Source code in src/torchio/data/image.py
def new_like(
    self,
    *,
    data: TypeImageData,
    affine: AffineMatrix | npt.ArrayLike | None = None,
) -> Self:
    r"""Create a new image of the same class with new data.

    Preserves metadata, annotations, and affine. Uses the existing
    affine unless a new one is provided. Works correctly with custom
    subclasses.

    Args:
        data: New 4D [`torch.Tensor`][torch.Tensor] with shape
            $(C, I, J, K)$.
        affine: New $4 \times 4$ affine. If `None`, uses `self.affine`.
    """
    new_affine = (
        self._parse_affine(affine) if affine is not None else self.affine.clone()
    )
    points_copy, bboxes_copy = self._deep_copy_annotations()
    return type(self)(
        data,
        affine=new_affine,
        points=points_copy,
        bounding_boxes=bboxes_copy,
        **dict(self._metadata),
    )

save(path, **kwargs)

Save the image to a file.

NIfTI-Zarr (.nii.zarr) files are written via niizarr (requires the zarr extra). All other formats are written with SimpleITK.

Parameters:

Name Type Description Default
path str | Path

Output file path. The format is inferred from the extension.

required
**kwargs Any

Extra keyword arguments forwarded to the writer. For SimpleITK formats these are passed to SimpleITK.WriteImage().

{}
Source code in src/torchio/data/image.py
def save(
    self,
    path: str | Path,
    **kwargs: Any,
) -> None:
    """Save the image to a file.

    NIfTI-Zarr (`.nii.zarr`) files are written via `niizarr`
    (requires the `zarr` extra). All other formats are written
    with [SimpleITK](https://simpleitk.org/).

    Args:
        path: Output file path. The format is inferred from the
            extension.
        **kwargs: Extra keyword arguments forwarded to the
            writer. For SimpleITK formats these are passed to
            `SimpleITK.WriteImage()`.
    """
    path = Path(path)
    if is_nifti_zarr(path):
        self._save_nii_zarr(path)
    else:
        self._save_sitk(path, **kwargs)

plot(**kwargs)

Plot 3 orthogonal slices of the image.

Requires the [plot] extras (pip install torchio[plot]). See plot_image for the full list of keyword arguments.

Source code in src/torchio/data/image.py
def plot(self, **kwargs: Any) -> Any:
    """Plot 3 orthogonal slices of the image.

    Requires the `[plot]` extras (`pip install torchio[plot]`).
    See [`plot_image`][torchio.visualization.plot_image] for the
    full list of keyword arguments.
    """
    from ..visualization import plot_image

    return plot_image(self, **kwargs)

plot_interactive(*, height=300)

Show an interactive NiiVue viewer in Jupyter.

Requires ipyniivue (pip install torchio[niivue]).

The widget supports scrolling through slices, zooming, and crosshair navigation. Left hemisphere is displayed on the right side of the screen (radiological convention).

Parameters:

Name Type Description Default
height int

Height of the viewer in pixels.

300

Returns:

Type Description
Any

An ipyniivue.NiiVue widget.

Raises:

Type Description
ImportError

If ipyniivue is not installed.

Source code in src/torchio/data/image.py
def plot_interactive(self, *, height: int = 300) -> Any:
    """Show an interactive NiiVue viewer in Jupyter.

    Requires `ipyniivue` (`pip install torchio[niivue]`).

    The widget supports scrolling through slices, zooming, and
    crosshair navigation.  Left hemisphere is displayed on the
    right side of the screen (radiological convention).

    Args:
        height: Height of the viewer in pixels.

    Returns:
        An `ipyniivue.NiiVue` widget.

    Raises:
        ImportError: If `ipyniivue` is not installed.
    """
    import tempfile

    import nibabel as nib
    import numpy as np

    from ..external.imports import get_ipyniivue

    nv = get_ipyniivue()

    data = self.data.cpu().float().numpy()
    if data.ndim == 4 and data.shape[0] == 1:
        data = data[0]
    affine = np.asarray(self.affine.data, dtype=np.float64)
    nii = nib.Nifti1Image(data, affine)
    with tempfile.NamedTemporaryFile(suffix=".nii.gz", delete=False) as f:
        nib.save(nii, f.name)
        path = f.name

    widget = nv.NiiVue(height=height)
    widget.opts.is_radiological_convention = True
    widget.add_volume(nv.Volume(path=path))
    return widget

to_gif(output_path=None, *, seconds=5.0, direction='I', loop=0, rescale=True, optimize=True, reverse=False)

Save an animated GIF sweeping through slices.

Requires Pillow (pip install torchio[plot]).

When output_path is None and the code is running inside a Jupyter notebook, the GIF is written to a temporary file and returned as an IPython.display.Image for inline display. Outside Jupyter, output_path is required.

Parameters:

Name Type Description Default
output_path str | Path | None

Path to the output .gif file. None to auto-create a temporary file (Jupyter only).

None
seconds float

Duration of the full animation in seconds.

5.0
direction str

Anatomical sweep direction ("I", "S", "A", "P", "R", or "L").

'I'
loop int

Number of loops (0 = infinite).

0
rescale bool

Rescale intensities to [0, 255].

True
optimize bool

Attempt to compress the GIF palette.

True
reverse bool

Reverse the temporal order of frames.

False

Returns:

Type Description
Any

IPython.display.Image when running in Jupyter,

Any

None otherwise.

Raises:

Type Description
ValueError

If output_path is None and the code is not running inside a Jupyter notebook.

Source code in src/torchio/data/image.py
def to_gif(
    self,
    output_path: str | Path | None = None,
    *,
    seconds: float = 5.0,
    direction: str = "I",
    loop: int = 0,
    rescale: bool = True,
    optimize: bool = True,
    reverse: bool = False,
) -> Any:
    """Save an animated GIF sweeping through slices.

    Requires `Pillow` (`pip install torchio[plot]`).

    When *output_path* is `None` and the code is running inside
    a Jupyter notebook, the GIF is written to a temporary file and
    returned as an `IPython.display.Image` for inline display.
    Outside Jupyter, *output_path* is required.

    Args:
        output_path: Path to the output `.gif` file.  `None`
            to auto-create a temporary file (Jupyter only).
        seconds: Duration of the full animation in seconds.
        direction: Anatomical sweep direction (`"I"`, `"S"`,
            `"A"`, `"P"`, `"R"`, or `"L"`).
        loop: Number of loops (0 = infinite).
        rescale: Rescale intensities to `[0, 255]`.
        optimize: Attempt to compress the GIF palette.
        reverse: Reverse the temporal order of frames.

    Returns:
        `IPython.display.Image` when running in Jupyter,
        `None` otherwise.

    Raises:
        ValueError: If *output_path* is `None` and the code is
            not running inside a Jupyter notebook.
    """
    output_path = _resolve_media_path(output_path, suffix=".gif")
    from ..visualization import make_gif

    make_gif(
        self,
        output_path,
        seconds=seconds,
        direction=direction,
        loop=loop,
        rescale=rescale,
        optimize=optimize,
        reverse=reverse,
    )
    if _in_jupyter():
        from IPython.display import Image as IPyImage

        return IPyImage(filename=str(output_path))
    return None

to_video(output_path=None, *, seconds=5.0, direction='I', verbosity='error')

Create an MP4 video sweeping through slices.

Requires ffmpeg-python (pip install torchio[video]).

When output_path is None and the code is running inside a Jupyter notebook, the video is written to a temporary file and returned as an IPython.display.Video for inline display. Outside Jupyter, output_path is required.

Parameters:

Name Type Description Default
output_path str | Path | None

Path to the output .mp4 file. None to auto-create a temporary file (Jupyter only).

None
seconds float

Duration of the full video in seconds.

5.0
direction str

Anatomical sweep direction ("I", "S", "A", "P", "R", or "L").

'I'
verbosity str

ffmpeg log level.

'error'

Returns:

Type Description
Any

IPython.display.Video when running in Jupyter,

Any

None otherwise.

Raises:

Type Description
ValueError

If output_path is None and the code is not running inside a Jupyter notebook.

Source code in src/torchio/data/image.py
def to_video(
    self,
    output_path: str | Path | None = None,
    *,
    seconds: float = 5.0,
    direction: str = "I",
    verbosity: str = "error",
) -> Any:
    """Create an MP4 video sweeping through slices.

    Requires `ffmpeg-python` (`pip install torchio[video]`).

    When *output_path* is `None` and the code is running inside
    a Jupyter notebook, the video is written to a temporary file
    and returned as an `IPython.display.Video` for inline
    display.  Outside Jupyter, *output_path* is required.

    Args:
        output_path: Path to the output `.mp4` file.  `None`
            to auto-create a temporary file (Jupyter only).
        seconds: Duration of the full video in seconds.
        direction: Anatomical sweep direction (`"I"`, `"S"`,
            `"A"`, `"P"`, `"R"`, or `"L"`).
        verbosity: ffmpeg log level.

    Returns:
        `IPython.display.Video` when running in Jupyter,
        `None` otherwise.

    Raises:
        ValueError: If *output_path* is `None` and the code is
            not running inside a Jupyter notebook.
    """
    output_path = _resolve_media_path(output_path, suffix=".mp4")
    from ..visualization import make_video

    make_video(
        self,
        output_path,
        seconds=seconds,
        direction=direction,
        verbosity=verbosity,
    )
    if _in_jupyter():
        from IPython.display import Video

        return Video(
            str(output_path),
            embed=True,
            html_attributes="controls autoplay loop muted",
        )
    return None

Image

Bases: Invertible

Base image class.

TorchIO images are lazy loaders: data is only read from disk when first accessed.

Use ScalarImage for intensity data and LabelMap for segmentations. Transforms use isinstance checks to decide behavior (e.g., nearest- neighbor interpolation for LabelMap).

The constructor accepts many source types and dispatches automatically:

Source type Behavior
str, Path, URL, OpenFile, file-like Lazy load from file
torch.Tensor, np.ndarray Eager, in-memory
nib.Nifti1Image Lazy via NibabelBackend
sitk.Image Eager, converted to tensor
zarr.abc.store.Store Lazy via zarr2nii + NibabelBackend
bytes, io.BytesIO Decoded via temp file
None (default) Empty image, set data later

Parameters:

Name Type Description Default
source ImageInput

Image data or path. See the table above.

None
reader Callable[[Path], tuple[TypeImageData, ndarray]] | None

Callable that takes a path and returns a tuple (tensor, affine_array). Overrides the default reader. Only used for file-path sources.

None
reader_kwargs dict[str, Any] | None

Extra keyword arguments forwarded to the reader function. For the default reader these are passed to nibabel.load() or SimpleITK.ReadImage().

None
affine AffineMatrix | ArrayLike | None

\(4 \times 4\) affine matrix or AffineMatrix instance. If given, overrides the affine read from the file.

None
channels_last bool

If True, the tensor is assumed to have shape \((I, J, K, C)\) and will be permuted to \((C, I, J, K)\). Only used for tensor sources.

False
suffix str | None

File suffix hint (e.g., ".nii.gz"). Used for file-like and bytes sources.

None
points dict[str, Points] | None

Named sets of Points attached to this image.

None
bounding_boxes dict[str, BoundingBoxes] | None

Named sets of BoundingBoxes attached to this image.

None
**kwargs Any

Arbitrary metadata, accessible via attribute or dict-style lookup (e.g., protocol="MPRAGE").

{}

Examples:

>>> import torchio as tio
>>> image = tio.ScalarImage("t1.nii.gz")  # from path (lazy)
>>> image = tio.ScalarImage(torch.randn(1, 256, 256, 176))  # from tensor
>>> image = tio.ScalarImage(nifti_image)  # from nibabel (lazy)
Source code in src/torchio/data/image.py
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
class Image(Invertible):
    r"""Base image class.

    TorchIO images are
    [lazy loaders](https://en.wikipedia.org/wiki/Lazy_loading):
    data is only read from disk when first accessed.

    Use [`ScalarImage`][torchio.ScalarImage] for intensity data and
    [`LabelMap`][torchio.LabelMap] for segmentations.
    Transforms use `isinstance` checks to decide behavior (e.g., nearest-
    neighbor interpolation for [`LabelMap`][torchio.LabelMap]).

    The constructor accepts many source types and dispatches
    automatically:

    | Source type | Behavior |
    |---|---|
    | `str`, `Path`, URL, `OpenFile`, file-like | Lazy load from file |
    | `torch.Tensor`, `np.ndarray` | Eager, in-memory |
    | `nib.Nifti1Image` | Lazy via `NibabelBackend` |
    | `sitk.Image` | Eager, converted to tensor |
    | `zarr.abc.store.Store` | Lazy via `zarr2nii` + `NibabelBackend` |
    | `bytes`, `io.BytesIO` | Decoded via temp file |
    | `None` (default) | Empty image, set data later |

    Args:
        source: Image data or path. See the table above.
        reader: Callable that takes a path and returns a tuple
            `(tensor, affine_array)`. Overrides the default reader.
            Only used for file-path sources.
        reader_kwargs: Extra keyword arguments forwarded to the reader
            function. For the default reader these are passed to
            `nibabel.load()` or `SimpleITK.ReadImage()`.
        affine: $4 \times 4$ affine matrix or
            [`AffineMatrix`][torchio.AffineMatrix] instance. If given, overrides
            the affine read from the file.
        channels_last: If `True`, the tensor is assumed to have
            shape $(I, J, K, C)$ and will be permuted to
            $(C, I, J, K)$. Only used for tensor sources.
        suffix: File suffix hint (e.g., `".nii.gz"`). Used for
            file-like and bytes sources.
        points: Named sets of [`Points`][torchio.Points] attached to
            this image.
        bounding_boxes: Named sets of
            [`BoundingBoxes`][torchio.BoundingBoxes] attached to this
            image.
        **kwargs: Arbitrary metadata, accessible via attribute or
            dict-style lookup (e.g., `protocol="MPRAGE"`).

    Examples:
        >>> import torchio as tio
        >>> image = tio.ScalarImage("t1.nii.gz")  # from path (lazy)
        >>> image = tio.ScalarImage(torch.randn(1, 256, 256, 176))  # from tensor
        >>> image = tio.ScalarImage(nifti_image)  # from nibabel (lazy)
    """

    #: Source types accepted by the constructor.
    ImageInput = (
        ImageSource  # str | Path | IOBase | OpenFile
        | Tensor
        | np.ndarray
        | nib.Nifti1Image
        | sitk.Image
        | bytes
        | io.BytesIO
        # | zarr.abc.store.Store  (optional, accepted at runtime)
        | None
    )

    def __init__(
        self,
        source: ImageInput = None,
        *,
        reader: Callable[[Path], tuple[TypeImageData, np.ndarray]] | None = None,
        reader_kwargs: dict[str, Any] | None = None,
        affine: AffineMatrix | npt.ArrayLike | None = None,
        channels_last: bool = False,
        suffix: str | None = None,
        points: dict[str, Points] | None = None,
        bounding_boxes: dict[str, BoundingBoxes] | None = None,
        **kwargs: Any,
    ):
        # Common state shared by all source types.
        self._reader = reader or default_reader
        self._reader_kwargs: dict[str, Any] = dict(reader_kwargs or {})
        self._channels_last = channels_last
        self._metadata: dict[str, Any] = dict(kwargs)
        self._data: Tensor | None = None
        self._backend: ImageDataBackend | None = None
        self._path: Path | None = None
        self._remote_zarr_uri: str | None = None
        self._zarr_store: Any = None
        self._affine: AffineMatrix | None = (
            self._parse_affine(affine) if affine is not None else None
        )
        self._points = self._parse_annotations(points, "Points")
        self._bounding_boxes = self._parse_annotations(
            bounding_boxes,
            "BoundingBoxes",
        )
        self.applied_transforms: list[Any] = []

        # Dispatch based on source type.
        self._dispatch_source(
            source, affine=affine, channels_last=channels_last, suffix=suffix
        )

    def _dispatch_source(
        self,
        source: ImageInput,
        *,
        affine: AffineMatrix | npt.ArrayLike | None,
        channels_last: bool,
        suffix: str | None,
    ) -> None:
        """Route *source* to the appropriate init helper."""
        if source is None:
            return
        if isinstance(source, (Tensor, np.ndarray)):
            self._init_from_tensor(source, affine=affine, channels_last=channels_last)
        elif isinstance(source, nib.Nifti1Image):
            self._init_from_nifti(source)
        elif isinstance(source, sitk.Image):
            self._init_from_sitk(source, affine=affine)
        elif isinstance(source, (bytes, io.BytesIO)):
            self._init_from_bytes(source, suffix=suffix or ".nii.gz")
        elif isinstance(source, str) and is_remote_nifti_zarr(source):
            self._remote_zarr_uri = source
        elif self._is_zarr_store(source):
            self._zarr_store = source
        else:
            # Path-like, URL, fsspec OpenFile, or file-like object.
            self._path = resolve_source(source, suffix=suffix)

    # -- Private init helpers -------------------------------------------------

    def _init_from_tensor(
        self,
        tensor: TypeImageData | np.ndarray,
        *,
        affine: AffineMatrix | npt.ArrayLike | None,
        channels_last: bool,
    ) -> None:
        parsed = self._parse_tensor(tensor)
        if channels_last:
            parsed = rearrange(parsed, "i j k c -> c i j k")
        self._data = parsed
        self._channels_last = False  # already permuted
        parsed_affine = self._parse_affine(affine)
        self._affine = parsed_affine
        self._backend = TensorBackend(self._data, affine=parsed_affine.data)

    def _init_from_nifti(self, nifti_image: nib.Nifti1Image) -> None:
        affine_override = self._affine.data if self._affine is not None else None
        self._backend = NibabelBackend(nifti_image, affine=affine_override)

    def _init_from_sitk(
        self,
        sitk_image: sitk.Image,
        *,
        affine: AffineMatrix | npt.ArrayLike | None,
    ) -> None:
        data = sitk.GetArrayFromImage(sitk_image)
        n_components = sitk_image.GetNumberOfComponentsPerPixel()
        data = data[np.newaxis] if n_components == 1 else np.moveaxis(data, -1, 0)
        from .io import _numpy_to_tensor

        tensor = _numpy_to_tensor(data.copy())
        spacing = np.array(sitk_image.GetSpacing())
        origin = np.array(sitk_image.GetOrigin())
        direction = rearrange(np.array(sitk_image.GetDirection()), "(i j) -> i j", i=3)
        affine_matrix = np.eye(4)
        affine_matrix[:3, :3] = direction * spacing
        affine_matrix[:3, 3] = origin
        self._init_from_tensor(
            tensor,
            affine=affine if affine is not None else AffineMatrix(affine_matrix),
            channels_last=False,
        )

    def _init_from_bytes(
        self,
        data: bytes | io.BytesIO,
        *,
        suffix: str,
    ) -> None:
        import tempfile

        if isinstance(data, io.BytesIO):
            data = data.read()
        with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
            tmp.write(data)
            tmp.flush()
            tmp_path = Path(tmp.name)
        try:
            nii = nib.load(tmp_path)
            if isinstance(nii, nib.Nifti1Image):
                self._init_from_nifti(nii)
                self.load()  # materialize before temp file is deleted
                return
            # Non-NIfTI: fall back to SimpleITK
            sitk_image = sitk.ReadImage(str(tmp_path))
            self._init_from_sitk(sitk_image, affine=self._affine)
        finally:
            tmp_path.unlink(missing_ok=True)

    @staticmethod
    def _is_zarr_store(obj: object) -> bool:
        """Check if *obj* is a `zarr.abc.store.Store` without importing zarr."""
        try:
            from zarr.abc.store import Store
        except ImportError:  # zarr not installed
            return False
        return isinstance(obj, Store)

    # -- Static helpers -------------------------------------------------------

    @staticmethod
    def _parse_tensor(tensor: Tensor | np.ndarray) -> Tensor:
        if isinstance(tensor, np.ndarray):
            from .io import _numpy_to_tensor

            tensor = _numpy_to_tensor(tensor.copy())
        if tensor.ndim != 4:
            msg = f"Tensor must be 4D (C, I, J, K), got {tensor.ndim}D"
            raise ValueError(msg)
        return tensor

    @staticmethod
    def _parse_affine(affine: AffineMatrix | npt.ArrayLike | None) -> AffineMatrix:
        if affine is None:
            return AffineMatrix()
        if isinstance(affine, AffineMatrix):
            return affine
        return AffineMatrix(affine)

    @staticmethod
    def _parse_annotations(
        annotations: dict[str, _AnnotationType] | None,
        type_name: str,
    ) -> dict[str, _AnnotationType]:
        """Validate and copy an annotation dict.

        Args:
            annotations: Mapping of names to annotation objects, or `None`.
            type_name: Expected class name (`"Points"` or
                `"BoundingBoxes"`) used for validation and error messages.

        Returns:
            A shallow copy of the dict, or an empty dict if *annotations*
            is `None`.

        Raises:
            TypeError: If any value is not an instance of the expected class.
        """
        if annotations is None:
            return {}
        expected_type = Points if type_name == "Points" else BoundingBoxes
        for key, value in annotations.items():
            if not isinstance(value, expected_type):
                msg = (
                    f"Expected {type_name} for key {key!r}, got {type(value).__name__}"
                )
                raise TypeError(msg)
        return dict(annotations)

    def _deep_copy_annotations(
        self,
    ) -> tuple[dict[str, Points], dict[str, BoundingBoxes]]:
        """Deep-copy both annotation dicts."""
        points_copy: dict[str, Points] = {
            k: copy.deepcopy(v) for k, v in self._points.items()
        }
        bboxes_copy: dict[str, BoundingBoxes] = {
            k: copy.deepcopy(v) for k, v in self._bounding_boxes.items()
        }
        return points_copy, bboxes_copy

    # --- Properties ---

    @property
    def path(self) -> Path | None:
        """Path to the image file, if any."""
        return self._path

    @property
    def is_loaded(self) -> bool:
        """Whether the image data is loaded into memory."""
        return self._data is not None

    @property
    def data(self) -> TypeImageData:
        """Tensor data with shape (C, I, J, K). Triggers lazy load if needed."""
        if self._data is None:
            self.load()
        assert self._data is not None
        return self._data

    @property
    def affine(self) -> AffineMatrix:
        """4x4 affine matrix mapping voxel indices to world coordinates."""
        if self._affine is None:
            # Try existing backend first to avoid full data load
            if self._backend is not None:
                self._affine = AffineMatrix(self._backend.affine)
            elif (
                self._remote_zarr_uri is not None
                or self._zarr_store is not None
                or (self._path is not None and self._reader_supports_lazy())
            ):
                self._ensure_backend()
                if self._backend is not None:
                    self._affine = AffineMatrix(self._backend.affine)
            if self._affine is None:
                self.load()
        assert self._affine is not None
        return self._affine

    @property
    def metadata(self) -> dict[str, Any]:
        """Arbitrary metadata dict."""
        return self._metadata

    @property
    def dataobj(self) -> ImageDataBackend:
        """Lazy data backend for advanced operations like slicing.

        Returns the underlying backend without materializing the full tensor.
        For NIfTI files this is a `NibabelBackend`; for NIfTI-Zarr files a
        `ZarrBackend`; for in-memory images a `TensorBackend`.
        """
        if self._backend is None:
            self._ensure_backend()
        assert self._backend is not None
        return self._backend

    @property
    def shape(self) -> TypeTensorShape:
        """Tensor shape as (C, I, J, K)."""
        if self._data is not None:
            c, si, sj, sk = self._data.shape
            return (c, si, sj, sk)
        if self._backend is not None:
            s = self._backend.shape
            return (int(s[0]), int(s[1]), int(s[2]), int(s[3]))
        if self._remote_zarr_uri is not None or self._zarr_store is not None:
            self._ensure_backend()
            assert self._backend is not None
            s = self._backend.shape
            return (int(s[0]), int(s[1]), int(s[2]), int(s[3]))
        if self._path is not None:
            if not self._reader_supports_lazy():
                self.load()
                return self.shape
            # Try to create a lazy backend (NIfTI, Zarr, or custom reader)
            self._ensure_backend()
            if self._backend is not None:
                s = self._backend.shape
                return (int(s[0]), int(s[1]), int(s[2]), int(s[3]))
            # Non-NIfTI: read shape from header via SimpleITK
            return self._read_shape_sitk(self._path)
        msg = "Cannot determine shape: no data or path"
        raise RuntimeError(msg)

    @property
    def spatial_shape(self) -> TypeSpatialShape:
        """Spatial dimensions as (I, J, K)."""
        return self.shape[1:]

    @property
    def num_channels(self) -> int:
        """Number of channels."""
        return self.shape[0]

    @property
    def spacing(self) -> tuple[float, float, float]:
        """Voxel spacing in mm, derived from the affine."""
        return self.affine.spacing

    @property
    def origin(self) -> tuple[float, float, float]:
        """Center of the first voxel in world coordinates."""
        return self.affine.origin

    @property
    def memory(self) -> int:
        """Number of bytes the tensor would occupy in RAM."""
        c, si, sj, sk = self.shape
        return c * si * sj * sk * self.dtype.itemsize

    @property
    def dtype(self) -> torch.dtype | np.dtype:
        """Data type of the image.

        Returns the PyTorch dtype if the image is loaded, otherwise
        reads the on-disk dtype from the header without loading data.
        """
        if self._data is not None:
            return self._data.dtype
        if self._backend is not None:
            return self._backend.dtype
        if self._remote_zarr_uri is not None:
            self._ensure_backend()
            if self._backend is not None:
                return self._backend.dtype
        if self._path is not None:
            self._ensure_backend()
            if self._backend is not None:
                return self._backend.dtype
            # Non-NIfTI fallback: read via SimpleITK header
            return self._read_dtype_sitk(self._path)
        msg = "Cannot determine dtype: no data or path"
        raise RuntimeError(msg)

    @property
    def orientation(self) -> tuple[str, str, str]:
        """Orientation codes from the affine."""
        return self.affine.orientation

    @property
    def points(self) -> dict[str, Points]:
        """Named sets of points attached to this image."""
        return self._points

    @property
    def bounding_boxes(self) -> dict[str, BoundingBoxes]:
        """Named sets of bounding boxes attached to this image."""
        return self._bounding_boxes

    # --- Methods ---

    def load(self) -> None:
        """Load data from disk into memory."""
        if self._data is not None:
            return
        if self._try_load_via_backend():
            return
        if self._path is None:
            msg = "Cannot load: no path or backend set"
            raise RuntimeError(msg)
        tensor, affine_array = self._reader(self._path, **self._reader_kwargs)
        self._data = tensor
        if self._affine is None:
            self._affine = AffineMatrix(affine_array)
        self._apply_channels_last()

    def _reader_supports_lazy(self) -> bool:
        """Whether the configured reader can provide a lazy backend.

        The default reader supports lazy NIfTI/NIfTI-Zarr access, and a custom
        reader does too if it implements
        [`LazyReader`][torchio.data.backends.LazyReader]. Simple `(tensor,
        affine)` readers do not and trigger a full load.
        """
        return self._reader is default_reader or isinstance(self._reader, LazyReader)

    def _try_load_via_backend(self) -> bool:
        """Try to load data from an existing or newly-created backend."""
        if self._load_from_backend():
            return True
        has_source = (
            self._remote_zarr_uri is not None
            or self._zarr_store is not None
            or self._path is not None
        )
        if has_source and self._reader_supports_lazy():
            self._ensure_backend()
            return self._load_from_backend()
        return False

    def _load_from_backend(self) -> bool:
        """Materialize data from the lazy backend if available."""
        if self._backend is None:
            return False
        self._data = self._backend.to_tensor()
        if self._affine is None:
            self._affine = AffineMatrix(self._backend.affine)
        self._apply_channels_last()
        return True

    def _apply_channels_last(self) -> None:
        """Permute data from (I, J, K, C) to (C, I, J, K) if needed."""
        if self._channels_last and self._data is not None:
            self._data = rearrange(self._data, "i j k c -> c i j k")
            self._channels_last = False  # only do it once

    def set_data(self, tensor: TypeImageData | np.ndarray) -> None:
        """Replace the image data with a new tensor.

        The lazy backend is refreshed so that `dataobj`, `dtype`, and
        `shape` stay coherent with the new tensor. The affine is preserved when
        one is set or can be read from the source header; for an image created
        without any source (e.g. `ScalarImage()` then `set_data`) it defaults to
        the identity affine.

        Args:
            tensor: 4D tensor with shape (C, I, J, K).
        """
        self._data = self._parse_tensor(tensor)
        self._refresh_backend_from_data()

    def _refresh_backend_from_data(self) -> None:
        """Rebuild the backend from the in-memory tensor.

        Once the data is held in memory it becomes the single source of
        truth, so the backend is replaced with a `TensorBackend` wrapping it.
        The affine is preserved: it is taken from the existing affine if set,
        otherwise resolved (header-only) from a lazy source, and finally
        defaults to identity for source-less images (e.g. created empty then
        filled with `set_data`). This never triggers a full data load.
        """
        assert self._data is not None
        if self._affine is None:
            self._affine = self._infer_affine_without_loading()
        self._backend = TensorBackend(self._data, affine=self._affine.data)

    def _infer_affine_without_loading(self) -> AffineMatrix:
        """Best-effort affine that never materializes the full tensor.

        Uses an existing or header-only lazy backend when available, and falls
        back to the identity affine when no affine source exists.
        """
        has_source = (
            self._backend is not None
            or self._path is not None
            or self._remote_zarr_uri is not None
            or self._zarr_store is not None
        )
        if has_source:
            if self._backend is None:
                self._ensure_backend()
            if self._backend is not None:
                return AffineMatrix(self._backend.affine)
        return AffineMatrix()

    @property
    def device(self) -> torch.device:
        """Device the image data resides on."""
        return self.data.device

    def to(self, *args: Any, **kwargs: Any) -> Self:
        """Move image data and affine to a device and/or cast to a dtype.

        Accepts the same arguments as `torch.Tensor.to()`.

        Returns:
            `self` (modified in-place).
        """
        self._data = self.data.to(*args, **kwargs)
        if self._affine is not None:
            self._affine.to(*args, **kwargs)
        self._refresh_backend_from_data()
        return self

    def numpy(self) -> np.ndarray:
        """Return the image data as a NumPy array.

        If the data is not loaded, reads it from disk first. The returned
        array shares memory with the tensor if possible (i.e., if the
        tensor is on CPU and not a view).

        Returns:
            4D array with shape (C, I, J, K).
        """
        return self.data.cpu().numpy()

    def new_like(
        self,
        *,
        data: TypeImageData,
        affine: AffineMatrix | npt.ArrayLike | None = None,
    ) -> Self:
        r"""Create a new image of the same class with new data.

        Preserves metadata, annotations, and affine. Uses the existing
        affine unless a new one is provided. Works correctly with custom
        subclasses.

        Args:
            data: New 4D [`torch.Tensor`][torch.Tensor] with shape
                $(C, I, J, K)$.
            affine: New $4 \times 4$ affine. If `None`, uses `self.affine`.
        """
        new_affine = (
            self._parse_affine(affine) if affine is not None else self.affine.clone()
        )
        points_copy, bboxes_copy = self._deep_copy_annotations()
        return type(self)(
            data,
            affine=new_affine,
            points=points_copy,
            bounding_boxes=bboxes_copy,
            **dict(self._metadata),
        )

    def save(
        self,
        path: str | Path,
        **kwargs: Any,
    ) -> None:
        """Save the image to a file.

        NIfTI-Zarr (`.nii.zarr`) files are written via `niizarr`
        (requires the `zarr` extra). All other formats are written
        with [SimpleITK](https://simpleitk.org/).

        Args:
            path: Output file path. The format is inferred from the
                extension.
            **kwargs: Extra keyword arguments forwarded to the
                writer. For SimpleITK formats these are passed to
                `SimpleITK.WriteImage()`.
        """
        path = Path(path)
        if is_nifti_zarr(path):
            self._save_nii_zarr(path)
        else:
            self._save_sitk(path, **kwargs)

    def _save_sitk(self, path: Path, **kwargs: Any) -> None:
        from .io import _RAS_TO_LPS

        data = self.numpy()
        n_channels = data.shape[0]
        if n_channels == 1:
            array = rearrange(data, "1 i j k -> k j i")
            sitk_image = sitk.GetImageFromArray(array)
        else:
            array = rearrange(data, "c i j k -> k j i c")
            sitk_image = sitk.GetImageFromArray(array, isVector=True)
        # Convert from RAS (TorchIO) to LPS (SimpleITK) before setting metadata.
        lps_affine = _RAS_TO_LPS @ self.affine.numpy()
        lps_spacing = np.sqrt(np.sum(lps_affine[:3, :3] ** 2, axis=0))
        lps_direction = lps_affine[:3, :3] / lps_spacing
        lps_origin = lps_affine[:3, 3]
        sitk_image.SetSpacing(lps_spacing.tolist())
        sitk_image.SetOrigin(lps_origin.tolist())
        sitk_image.SetDirection(lps_direction.ravel().tolist())
        sitk.WriteImage(sitk_image, str(path), **kwargs)

    def _save_nii_zarr(self, path: Path) -> None:
        niizarr = get_niizarr()
        data = self.data.numpy()
        n_channels = data.shape[0]
        if n_channels == 1:
            array = rearrange(data, "1 i j k -> i j k")
        else:
            array = rearrange(data, "c i j k -> i j k c")
        nii = nib.Nifti1Image(array, self.affine.numpy())
        niizarr.nii2zarr(nii, str(path))

    def _ensure_backend(self) -> None:
        """Create the lazy backend from path or zarr store, without loading data.

        Backend selection is delegated to
        [`resolve_backend`][torchio.data.backends.resolve_backend], which
        consults the backend registry. For NIfTI and NIfTI-Zarr sources this
        yields a header-only lazy backend; for other formats (NRRD, MHA, etc.)
        no lazy backend is available and `_backend` is left unset so callers
        fall back to a full read.
        """
        if self._backend is not None:
            return
        affine_override = self._affine.data if self._affine is not None else None
        request = BackendRequest(
            path=self._path,
            remote_zarr_uri=self._remote_zarr_uri,
            zarr_store=self._zarr_store,
            affine=affine_override,
            reader_kwargs=self._reader_kwargs,
            reader=self._reader,
        )
        backend = resolve_backend(request)
        if backend is not None:
            self._backend = backend
            return
        if (
            self._path is None
            and self._remote_zarr_uri is None
            and self._zarr_store is None
        ):
            msg = "Cannot create backend: no path or store set"
            raise RuntimeError(msg)

    @staticmethod
    def _read_shape_sitk(path: Path) -> TypeTensorShape:
        """Read shape from a SimpleITK-readable file without loading data."""
        reader = sitk.ImageFileReader()
        reader.SetFileName(str(path))
        reader.ReadImageInformation()
        size = reader.GetSize()
        n_components = reader.GetNumberOfComponents()
        ndim = reader.GetDimension()
        if ndim == 3:
            return (n_components, size[0], size[1], size[2])
        msg = f"Expected 3D image, got {ndim}D"
        raise ValueError(msg)

    @staticmethod
    def _read_dtype_sitk(path: Path) -> np.dtype:
        """Read dtype from a SimpleITK-readable file without loading data."""
        reader = sitk.ImageFileReader()
        reader.SetFileName(str(path))
        reader.ReadImageInformation()
        pixel_id = reader.GetPixelID()
        # Map SimpleITK pixel IDs to numpy dtypes
        sitk_to_numpy = {
            sitk.sitkUInt8: np.dtype("uint8"),
            sitk.sitkInt8: np.dtype("int8"),
            sitk.sitkUInt16: np.dtype("uint16"),
            sitk.sitkInt16: np.dtype("int16"),
            sitk.sitkUInt32: np.dtype("uint32"),
            sitk.sitkInt32: np.dtype("int32"),
            sitk.sitkUInt64: np.dtype("uint64"),
            sitk.sitkInt64: np.dtype("int64"),
            sitk.sitkFloat32: np.dtype("float32"),
            sitk.sitkFloat64: np.dtype("float64"),
            sitk.sitkVectorUInt8: np.dtype("uint8"),
            sitk.sitkVectorInt8: np.dtype("int8"),
            sitk.sitkVectorUInt16: np.dtype("uint16"),
            sitk.sitkVectorInt16: np.dtype("int16"),
            sitk.sitkVectorUInt32: np.dtype("uint32"),
            sitk.sitkVectorInt32: np.dtype("int32"),
            sitk.sitkVectorFloat32: np.dtype("float32"),
            sitk.sitkVectorFloat64: np.dtype("float64"),
        }
        return sitk_to_numpy.get(pixel_id, np.dtype("float32"))

    def __getitem__(
        self,
        item: str | int | slice | tuple[int | slice, ...],
    ) -> Any:
        """Slice the image or look up metadata by key.

        When *item* is a `str`, the metadata value with that key is
        returned. Otherwise, the image is sliced along channel and/or
        spatial dimensions.

        Indexing follows the tensor layout `(C, I, J, K)`. Up to four
        indices may be provided; unspecified trailing dimensions keep
        their full extent. The affine origin is updated to reflect the
        spatial crop. Ellipsis (`...`) expands to fill unspecified
        dimensions with full slices. Negative indices and steps are
        supported.

        When the image has not been loaded yet, slicing reads only the
        requested region through the lazy backend. The full tensor is
        never materialized. For uncompressed NIfTI (`.nii`) this uses
        memory-mapping; for NIfTI-Zarr (`.nii.zarr`) chunked reads.
        Even for compressed NIfTI (`.nii.gz`), nibabel's proxy avoids
        materializing the full array, so slicing a small region from a
        large volume is much faster than loading everything first.

        Args:
            item: Integer, slice, or tuple of slices/ints/ellipsis for
                the C, I, J, K dimensions.

        Returns:
            A new image of the same class containing the sliced data.

        Examples:
            >>> image = tio.ScalarImage(torch.randn(3, 256, 256, 176))
            >>> image[0].shape              # first channel
            (1, 256, 256, 176)
            >>> image[:, 100:200].shape     # spatial range, all channels
            (3, 100, 256, 176)
            >>> image[..., 50:100].shape    # last spatial dim
            (3, 256, 256, 50)
            >>> image[1:3, 10:20, 10:20, 10:20].shape
            (2, 10, 10, 10)
        """
        # String key → metadata lookup
        if isinstance(item, str):
            if item in self._metadata:
                return self._metadata[item]
            msg = f"{type(self).__name__} has no metadata key {item!r}"
            raise KeyError(msg)

        sc, si, sj, sk = normalize_index(item)

        full_shape = self.shape
        cropped_data = self._slice_data(sc, si, sj, sk)

        # Update affine origin: shift by the spatial start offset
        affine_matrix = self.affine.data.clone()
        i_start, _, _ = si.indices(full_shape[1])
        j_start, _, _ = sj.indices(full_shape[2])
        k_start, _, _ = sk.indices(full_shape[3])
        start_voxel = torch.tensor(
            [i_start, j_start, k_start],
            dtype=torch.float64,
            device=affine_matrix.device,
        )
        affine_matrix[:3, 3] += affine_matrix[:3, :3] @ start_voxel

        return self.new_like(data=cropped_data, affine=AffineMatrix(affine_matrix))

    def _slice_data(
        self,
        sc: slice,
        si: slice,
        sj: slice,
        sk: slice,
    ) -> Tensor:
        """Slice data, using the lazy backend if available."""
        if self._data is not None:
            return self._data[sc, si, sj, sk]
        self._ensure_backend()
        if self._backend is not None:
            return self._backend[sc, si, sj, sk]
        return self.data[sc, si, sj, sk]

    def _repr_path_line(self) -> str:
        """Build the `path:` line for `__repr__`."""
        if self._remote_zarr_uri is not None:
            status = "loaded" if self.is_loaded else "lazy, NIfTI-Zarr"
            return f"    path:        {self._remote_zarr_uri} ({status})"
        if self._path is not None:
            name = self._path.name
            if self.is_loaded:
                return f"    path:        {name} (loaded)"
            fmt = _backend_label(self._backend)
            return f"    path:        {name} (lazy, {fmt})"
        return "    path:        (in memory)"

    def __repr__(self) -> str:
        import humanize

        cls_name = type(self).__name__
        lines: list[str] = []
        try:
            sp = ", ".join(f"{s:.2f}" for s in self.spacing)
            ori = ", ".join(f"{o:.2f}" for o in self.origin)
            angles = ", ".join(f"{a:.1f}°" for a in self.affine.euler_angles)
            dt = str(self.dtype).replace("torch.", "")
            mem = humanize.naturalsize(self.memory, binary=True)

            # Path / loading status (after header read so backend is set)
            lines.append(self._repr_path_line())

            lines.append(f"    channels:    {self.num_channels}")
            lines.append(f"    spatial:     {self.spatial_shape}")
            lines.append(f"    spacing:     ({sp}) mm")
            lines.append(f"    origin:      ({ori}) mm")
            lines.append(f"    orientation: {''.join(self.orientation)}+")
            lines.append(f"    angles:      ({angles})")
            lines.append(f"    dtype:       {dt}")
            if self.is_loaded:
                lines.append(f"    device:      {self.device}")
            lines.append(f"    memory:      {mem}")
        except Exception:
            if self._path is not None:
                lines.append(f'    path: "{self._path}"')

        if self._points:
            names = ", ".join(self._points)
            lines.append(f"    points:      {{{names}}}")
        if self._bounding_boxes:
            names = ", ".join(self._bounding_boxes)
            lines.append(f"    bboxes:      {{{names}}}")

        body = "\n".join(lines)
        return f"{cls_name}(\n{body}\n)"

    def _repr_html_(self) -> str:
        """Rich HTML representation for Jupyter notebooks."""
        from ..repr_html import image_to_html

        return image_to_html(self)

    def plot(self, **kwargs: Any) -> Any:
        """Plot 3 orthogonal slices of the image.

        Requires the `[plot]` extras (`pip install torchio[plot]`).
        See [`plot_image`][torchio.visualization.plot_image] for the
        full list of keyword arguments.
        """
        from ..visualization import plot_image

        return plot_image(self, **kwargs)

    def plot_interactive(self, *, height: int = 300) -> Any:
        """Show an interactive NiiVue viewer in Jupyter.

        Requires `ipyniivue` (`pip install torchio[niivue]`).

        The widget supports scrolling through slices, zooming, and
        crosshair navigation.  Left hemisphere is displayed on the
        right side of the screen (radiological convention).

        Args:
            height: Height of the viewer in pixels.

        Returns:
            An `ipyniivue.NiiVue` widget.

        Raises:
            ImportError: If `ipyniivue` is not installed.
        """
        import tempfile

        import nibabel as nib
        import numpy as np

        from ..external.imports import get_ipyniivue

        nv = get_ipyniivue()

        data = self.data.cpu().float().numpy()
        if data.ndim == 4 and data.shape[0] == 1:
            data = data[0]
        affine = np.asarray(self.affine.data, dtype=np.float64)
        nii = nib.Nifti1Image(data, affine)
        with tempfile.NamedTemporaryFile(suffix=".nii.gz", delete=False) as f:
            nib.save(nii, f.name)
            path = f.name

        widget = nv.NiiVue(height=height)
        widget.opts.is_radiological_convention = True
        widget.add_volume(nv.Volume(path=path))
        return widget

    def to_gif(
        self,
        output_path: str | Path | None = None,
        *,
        seconds: float = 5.0,
        direction: str = "I",
        loop: int = 0,
        rescale: bool = True,
        optimize: bool = True,
        reverse: bool = False,
    ) -> Any:
        """Save an animated GIF sweeping through slices.

        Requires `Pillow` (`pip install torchio[plot]`).

        When *output_path* is `None` and the code is running inside
        a Jupyter notebook, the GIF is written to a temporary file and
        returned as an `IPython.display.Image` for inline display.
        Outside Jupyter, *output_path* is required.

        Args:
            output_path: Path to the output `.gif` file.  `None`
                to auto-create a temporary file (Jupyter only).
            seconds: Duration of the full animation in seconds.
            direction: Anatomical sweep direction (`"I"`, `"S"`,
                `"A"`, `"P"`, `"R"`, or `"L"`).
            loop: Number of loops (0 = infinite).
            rescale: Rescale intensities to `[0, 255]`.
            optimize: Attempt to compress the GIF palette.
            reverse: Reverse the temporal order of frames.

        Returns:
            `IPython.display.Image` when running in Jupyter,
            `None` otherwise.

        Raises:
            ValueError: If *output_path* is `None` and the code is
                not running inside a Jupyter notebook.
        """
        output_path = _resolve_media_path(output_path, suffix=".gif")
        from ..visualization import make_gif

        make_gif(
            self,
            output_path,
            seconds=seconds,
            direction=direction,
            loop=loop,
            rescale=rescale,
            optimize=optimize,
            reverse=reverse,
        )
        if _in_jupyter():
            from IPython.display import Image as IPyImage

            return IPyImage(filename=str(output_path))
        return None

    def to_video(
        self,
        output_path: str | Path | None = None,
        *,
        seconds: float = 5.0,
        direction: str = "I",
        verbosity: str = "error",
    ) -> Any:
        """Create an MP4 video sweeping through slices.

        Requires `ffmpeg-python` (`pip install torchio[video]`).

        When *output_path* is `None` and the code is running inside
        a Jupyter notebook, the video is written to a temporary file
        and returned as an `IPython.display.Video` for inline
        display.  Outside Jupyter, *output_path* is required.

        Args:
            output_path: Path to the output `.mp4` file.  `None`
                to auto-create a temporary file (Jupyter only).
            seconds: Duration of the full video in seconds.
            direction: Anatomical sweep direction (`"I"`, `"S"`,
                `"A"`, `"P"`, `"R"`, or `"L"`).
            verbosity: ffmpeg log level.

        Returns:
            `IPython.display.Video` when running in Jupyter,
            `None` otherwise.

        Raises:
            ValueError: If *output_path* is `None` and the code is
                not running inside a Jupyter notebook.
        """
        output_path = _resolve_media_path(output_path, suffix=".mp4")
        from ..visualization import make_video

        make_video(
            self,
            output_path,
            seconds=seconds,
            direction=direction,
            verbosity=verbosity,
        )
        if _in_jupyter():
            from IPython.display import Video

            return Video(
                str(output_path),
                embed=True,
                html_attributes="controls autoplay loop muted",
            )
        return None

    def __getattr__(self, name: str) -> Any:
        """Look up metadata by attribute name."""
        if name.startswith("_"):
            raise AttributeError(name)
        if name in self._metadata:
            return self._metadata[name]
        msg = f"{type(self).__name__} has no attribute {name!r}"
        raise AttributeError(msg)

    def __copy__(self) -> Self:
        return self.new_like(data=self.data.clone())

    def __deepcopy__(self, memo: dict) -> Self:
        affine_copy = copy.deepcopy(self._affine) if self._affine is not None else None
        meta_copy = dict(self._metadata)
        points_copy, bboxes_copy = self._deep_copy_annotations()

        if self._remote_zarr_uri is not None:
            new = type(self)(
                self._remote_zarr_uri,
                reader=self._reader,
                reader_kwargs=dict(self._reader_kwargs),
                affine=affine_copy,
                points=points_copy,
                bounding_boxes=bboxes_copy,
                **meta_copy,
            )
            if self._data is not None:
                new._data = self._data.clone()
                new._affine = affine_copy
        elif self._path is not None:
            new = type(self)(
                self._path,
                reader=self._reader,
                reader_kwargs=dict(self._reader_kwargs),
                affine=affine_copy,
                points=points_copy,
                bounding_boxes=bboxes_copy,
                **meta_copy,
            )
            if self._data is not None:
                new._data = self._data.clone()
                new._affine = affine_copy
            # Backend will be lazily recreated from path when needed
        elif self._zarr_store is not None:
            new = type(self)(
                self._zarr_store,
                reader_kwargs=dict(self._reader_kwargs),
                affine=affine_copy,
                points=points_copy,
                bounding_boxes=bboxes_copy,
                **meta_copy,
            )
            if self._data is not None:
                new._data = self._data.clone()
                new._affine = affine_copy
        elif self._data is not None:
            new = type(self)(
                self._data.clone(),
                affine=affine_copy,
                points=points_copy,
                bounding_boxes=bboxes_copy,
                **meta_copy,
            )
        else:
            new = type(self)(
                affine=affine_copy,
                points=points_copy,
                bounding_boxes=bboxes_copy,
                **meta_copy,
            )
        memo[id(self)] = new
        return new

path property

Path to the image file, if any.

is_loaded property

Whether the image data is loaded into memory.

data property

Tensor data with shape (C, I, J, K). Triggers lazy load if needed.

affine property

4x4 affine matrix mapping voxel indices to world coordinates.

metadata property

Arbitrary metadata dict.

dataobj property

Lazy data backend for advanced operations like slicing.

Returns the underlying backend without materializing the full tensor. For NIfTI files this is a NibabelBackend; for NIfTI-Zarr files a ZarrBackend; for in-memory images a TensorBackend.

shape property

Tensor shape as (C, I, J, K).

spatial_shape property

Spatial dimensions as (I, J, K).

num_channels property

Number of channels.

spacing property

Voxel spacing in mm, derived from the affine.

origin property

Center of the first voxel in world coordinates.

memory property

Number of bytes the tensor would occupy in RAM.

dtype property

Data type of the image.

Returns the PyTorch dtype if the image is loaded, otherwise reads the on-disk dtype from the header without loading data.

orientation property

Orientation codes from the affine.

points property

Named sets of points attached to this image.

bounding_boxes property

Named sets of bounding boxes attached to this image.

device property

Device the image data resides on.

get_inverse_transform(*, warn=True, ignore_intensity=False)

Get a composed transform that inverts the applied history.

Returns a Compose of the inverse of each applied transform, in reverse order. Non-invertible transforms are skipped (with a warning if warn=True).

Parameters:

Name Type Description Default
warn bool

Issue a warning for non-invertible transforms.

True
ignore_intensity bool

Skip all intensity transforms.

False

Returns:

Type Description
Any

A Compose transform that undoes the history.

Source code in src/torchio/data/invertible.py
def get_inverse_transform(
    self,
    *,
    warn: bool = True,
    ignore_intensity: bool = False,
) -> Any:
    """Get a composed transform that inverts the applied history.

    Returns a [`Compose`][torchio.Compose] of the inverse of each
    applied transform, in reverse order. Non-invertible transforms
    are skipped (with a warning if `warn=True`).

    Args:
        warn: Issue a warning for non-invertible transforms.
        ignore_intensity: Skip all intensity transforms.

    Returns:
        A `Compose` transform that undoes the history.
    """
    from ..transforms.inverse import get_inverse_transform

    return get_inverse_transform(
        self.applied_transforms,
        warn=warn,
        ignore_intensity=ignore_intensity,
    )

apply_inverse_transform(**kwargs)

Apply the inverse of all applied transforms, in reverse order.

Non-invertible transforms are skipped. Intensity transforms can be ignored with ignore_intensity=True.

Parameters:

Name Type Description Default
**kwargs Any

Forwarded to get_inverse_transform() (warn, ignore_intensity).

{}

Returns:

Type Description
Self

Data with transforms undone.

Examples:

>>> transformed = transform(subject)
>>> restored = transformed.apply_inverse_transform()
Source code in src/torchio/data/invertible.py
def apply_inverse_transform(self, **kwargs: Any) -> Self:
    """Apply the inverse of all applied transforms, in reverse order.

    Non-invertible transforms are skipped. Intensity transforms
    can be ignored with `ignore_intensity=True`.

    Args:
        **kwargs: Forwarded to
            `get_inverse_transform()` (`warn`,
            `ignore_intensity`).

    Returns:
        Data with transforms undone.

    Examples:
        >>> transformed = transform(subject)
        >>> restored = transformed.apply_inverse_transform()
    """
    inverse_transform = self.get_inverse_transform(**kwargs)
    result = inverse_transform(self)
    if hasattr(result, "applied_transforms"):
        result.applied_transforms = []
    return result

clear_history()

Remove all applied transform records.

Source code in src/torchio/data/invertible.py
def clear_history(self) -> None:
    """Remove all applied transform records."""
    self.applied_transforms = []

load()

Load data from disk into memory.

Source code in src/torchio/data/image.py
def load(self) -> None:
    """Load data from disk into memory."""
    if self._data is not None:
        return
    if self._try_load_via_backend():
        return
    if self._path is None:
        msg = "Cannot load: no path or backend set"
        raise RuntimeError(msg)
    tensor, affine_array = self._reader(self._path, **self._reader_kwargs)
    self._data = tensor
    if self._affine is None:
        self._affine = AffineMatrix(affine_array)
    self._apply_channels_last()

set_data(tensor)

Replace the image data with a new tensor.

The lazy backend is refreshed so that dataobj, dtype, and shape stay coherent with the new tensor. The affine is preserved when one is set or can be read from the source header; for an image created without any source (e.g. ScalarImage() then set_data) it defaults to the identity affine.

Parameters:

Name Type Description Default
tensor TypeImageData | ndarray

4D tensor with shape (C, I, J, K).

required
Source code in src/torchio/data/image.py
def set_data(self, tensor: TypeImageData | np.ndarray) -> None:
    """Replace the image data with a new tensor.

    The lazy backend is refreshed so that `dataobj`, `dtype`, and
    `shape` stay coherent with the new tensor. The affine is preserved when
    one is set or can be read from the source header; for an image created
    without any source (e.g. `ScalarImage()` then `set_data`) it defaults to
    the identity affine.

    Args:
        tensor: 4D tensor with shape (C, I, J, K).
    """
    self._data = self._parse_tensor(tensor)
    self._refresh_backend_from_data()

to(*args, **kwargs)

Move image data and affine to a device and/or cast to a dtype.

Accepts the same arguments as torch.Tensor.to().

Returns:

Type Description
Self

self (modified in-place).

Source code in src/torchio/data/image.py
def to(self, *args: Any, **kwargs: Any) -> Self:
    """Move image data and affine to a device and/or cast to a dtype.

    Accepts the same arguments as `torch.Tensor.to()`.

    Returns:
        `self` (modified in-place).
    """
    self._data = self.data.to(*args, **kwargs)
    if self._affine is not None:
        self._affine.to(*args, **kwargs)
    self._refresh_backend_from_data()
    return self

numpy()

Return the image data as a NumPy array.

If the data is not loaded, reads it from disk first. The returned array shares memory with the tensor if possible (i.e., if the tensor is on CPU and not a view).

Returns:

Type Description
ndarray

4D array with shape (C, I, J, K).

Source code in src/torchio/data/image.py
def numpy(self) -> np.ndarray:
    """Return the image data as a NumPy array.

    If the data is not loaded, reads it from disk first. The returned
    array shares memory with the tensor if possible (i.e., if the
    tensor is on CPU and not a view).

    Returns:
        4D array with shape (C, I, J, K).
    """
    return self.data.cpu().numpy()

new_like(*, data, affine=None)

Create a new image of the same class with new data.

Preserves metadata, annotations, and affine. Uses the existing affine unless a new one is provided. Works correctly with custom subclasses.

Parameters:

Name Type Description Default
data TypeImageData

New 4D torch.Tensor with shape \((C, I, J, K)\).

required
affine AffineMatrix | ArrayLike | None

New \(4 \times 4\) affine. If None, uses self.affine.

None
Source code in src/torchio/data/image.py
def new_like(
    self,
    *,
    data: TypeImageData,
    affine: AffineMatrix | npt.ArrayLike | None = None,
) -> Self:
    r"""Create a new image of the same class with new data.

    Preserves metadata, annotations, and affine. Uses the existing
    affine unless a new one is provided. Works correctly with custom
    subclasses.

    Args:
        data: New 4D [`torch.Tensor`][torch.Tensor] with shape
            $(C, I, J, K)$.
        affine: New $4 \times 4$ affine. If `None`, uses `self.affine`.
    """
    new_affine = (
        self._parse_affine(affine) if affine is not None else self.affine.clone()
    )
    points_copy, bboxes_copy = self._deep_copy_annotations()
    return type(self)(
        data,
        affine=new_affine,
        points=points_copy,
        bounding_boxes=bboxes_copy,
        **dict(self._metadata),
    )

save(path, **kwargs)

Save the image to a file.

NIfTI-Zarr (.nii.zarr) files are written via niizarr (requires the zarr extra). All other formats are written with SimpleITK.

Parameters:

Name Type Description Default
path str | Path

Output file path. The format is inferred from the extension.

required
**kwargs Any

Extra keyword arguments forwarded to the writer. For SimpleITK formats these are passed to SimpleITK.WriteImage().

{}
Source code in src/torchio/data/image.py
def save(
    self,
    path: str | Path,
    **kwargs: Any,
) -> None:
    """Save the image to a file.

    NIfTI-Zarr (`.nii.zarr`) files are written via `niizarr`
    (requires the `zarr` extra). All other formats are written
    with [SimpleITK](https://simpleitk.org/).

    Args:
        path: Output file path. The format is inferred from the
            extension.
        **kwargs: Extra keyword arguments forwarded to the
            writer. For SimpleITK formats these are passed to
            `SimpleITK.WriteImage()`.
    """
    path = Path(path)
    if is_nifti_zarr(path):
        self._save_nii_zarr(path)
    else:
        self._save_sitk(path, **kwargs)

plot(**kwargs)

Plot 3 orthogonal slices of the image.

Requires the [plot] extras (pip install torchio[plot]). See plot_image for the full list of keyword arguments.

Source code in src/torchio/data/image.py
def plot(self, **kwargs: Any) -> Any:
    """Plot 3 orthogonal slices of the image.

    Requires the `[plot]` extras (`pip install torchio[plot]`).
    See [`plot_image`][torchio.visualization.plot_image] for the
    full list of keyword arguments.
    """
    from ..visualization import plot_image

    return plot_image(self, **kwargs)

plot_interactive(*, height=300)

Show an interactive NiiVue viewer in Jupyter.

Requires ipyniivue (pip install torchio[niivue]).

The widget supports scrolling through slices, zooming, and crosshair navigation. Left hemisphere is displayed on the right side of the screen (radiological convention).

Parameters:

Name Type Description Default
height int

Height of the viewer in pixels.

300

Returns:

Type Description
Any

An ipyniivue.NiiVue widget.

Raises:

Type Description
ImportError

If ipyniivue is not installed.

Source code in src/torchio/data/image.py
def plot_interactive(self, *, height: int = 300) -> Any:
    """Show an interactive NiiVue viewer in Jupyter.

    Requires `ipyniivue` (`pip install torchio[niivue]`).

    The widget supports scrolling through slices, zooming, and
    crosshair navigation.  Left hemisphere is displayed on the
    right side of the screen (radiological convention).

    Args:
        height: Height of the viewer in pixels.

    Returns:
        An `ipyniivue.NiiVue` widget.

    Raises:
        ImportError: If `ipyniivue` is not installed.
    """
    import tempfile

    import nibabel as nib
    import numpy as np

    from ..external.imports import get_ipyniivue

    nv = get_ipyniivue()

    data = self.data.cpu().float().numpy()
    if data.ndim == 4 and data.shape[0] == 1:
        data = data[0]
    affine = np.asarray(self.affine.data, dtype=np.float64)
    nii = nib.Nifti1Image(data, affine)
    with tempfile.NamedTemporaryFile(suffix=".nii.gz", delete=False) as f:
        nib.save(nii, f.name)
        path = f.name

    widget = nv.NiiVue(height=height)
    widget.opts.is_radiological_convention = True
    widget.add_volume(nv.Volume(path=path))
    return widget

to_gif(output_path=None, *, seconds=5.0, direction='I', loop=0, rescale=True, optimize=True, reverse=False)

Save an animated GIF sweeping through slices.

Requires Pillow (pip install torchio[plot]).

When output_path is None and the code is running inside a Jupyter notebook, the GIF is written to a temporary file and returned as an IPython.display.Image for inline display. Outside Jupyter, output_path is required.

Parameters:

Name Type Description Default
output_path str | Path | None

Path to the output .gif file. None to auto-create a temporary file (Jupyter only).

None
seconds float

Duration of the full animation in seconds.

5.0
direction str

Anatomical sweep direction ("I", "S", "A", "P", "R", or "L").

'I'
loop int

Number of loops (0 = infinite).

0
rescale bool

Rescale intensities to [0, 255].

True
optimize bool

Attempt to compress the GIF palette.

True
reverse bool

Reverse the temporal order of frames.

False

Returns:

Type Description
Any

IPython.display.Image when running in Jupyter,

Any

None otherwise.

Raises:

Type Description
ValueError

If output_path is None and the code is not running inside a Jupyter notebook.

Source code in src/torchio/data/image.py
def to_gif(
    self,
    output_path: str | Path | None = None,
    *,
    seconds: float = 5.0,
    direction: str = "I",
    loop: int = 0,
    rescale: bool = True,
    optimize: bool = True,
    reverse: bool = False,
) -> Any:
    """Save an animated GIF sweeping through slices.

    Requires `Pillow` (`pip install torchio[plot]`).

    When *output_path* is `None` and the code is running inside
    a Jupyter notebook, the GIF is written to a temporary file and
    returned as an `IPython.display.Image` for inline display.
    Outside Jupyter, *output_path* is required.

    Args:
        output_path: Path to the output `.gif` file.  `None`
            to auto-create a temporary file (Jupyter only).
        seconds: Duration of the full animation in seconds.
        direction: Anatomical sweep direction (`"I"`, `"S"`,
            `"A"`, `"P"`, `"R"`, or `"L"`).
        loop: Number of loops (0 = infinite).
        rescale: Rescale intensities to `[0, 255]`.
        optimize: Attempt to compress the GIF palette.
        reverse: Reverse the temporal order of frames.

    Returns:
        `IPython.display.Image` when running in Jupyter,
        `None` otherwise.

    Raises:
        ValueError: If *output_path* is `None` and the code is
            not running inside a Jupyter notebook.
    """
    output_path = _resolve_media_path(output_path, suffix=".gif")
    from ..visualization import make_gif

    make_gif(
        self,
        output_path,
        seconds=seconds,
        direction=direction,
        loop=loop,
        rescale=rescale,
        optimize=optimize,
        reverse=reverse,
    )
    if _in_jupyter():
        from IPython.display import Image as IPyImage

        return IPyImage(filename=str(output_path))
    return None

to_video(output_path=None, *, seconds=5.0, direction='I', verbosity='error')

Create an MP4 video sweeping through slices.

Requires ffmpeg-python (pip install torchio[video]).

When output_path is None and the code is running inside a Jupyter notebook, the video is written to a temporary file and returned as an IPython.display.Video for inline display. Outside Jupyter, output_path is required.

Parameters:

Name Type Description Default
output_path str | Path | None

Path to the output .mp4 file. None to auto-create a temporary file (Jupyter only).

None
seconds float

Duration of the full video in seconds.

5.0
direction str

Anatomical sweep direction ("I", "S", "A", "P", "R", or "L").

'I'
verbosity str

ffmpeg log level.

'error'

Returns:

Type Description
Any

IPython.display.Video when running in Jupyter,

Any

None otherwise.

Raises:

Type Description
ValueError

If output_path is None and the code is not running inside a Jupyter notebook.

Source code in src/torchio/data/image.py
def to_video(
    self,
    output_path: str | Path | None = None,
    *,
    seconds: float = 5.0,
    direction: str = "I",
    verbosity: str = "error",
) -> Any:
    """Create an MP4 video sweeping through slices.

    Requires `ffmpeg-python` (`pip install torchio[video]`).

    When *output_path* is `None` and the code is running inside
    a Jupyter notebook, the video is written to a temporary file
    and returned as an `IPython.display.Video` for inline
    display.  Outside Jupyter, *output_path* is required.

    Args:
        output_path: Path to the output `.mp4` file.  `None`
            to auto-create a temporary file (Jupyter only).
        seconds: Duration of the full video in seconds.
        direction: Anatomical sweep direction (`"I"`, `"S"`,
            `"A"`, `"P"`, `"R"`, or `"L"`).
        verbosity: ffmpeg log level.

    Returns:
        `IPython.display.Video` when running in Jupyter,
        `None` otherwise.

    Raises:
        ValueError: If *output_path* is `None` and the code is
            not running inside a Jupyter notebook.
    """
    output_path = _resolve_media_path(output_path, suffix=".mp4")
    from ..visualization import make_video

    make_video(
        self,
        output_path,
        seconds=seconds,
        direction=direction,
        verbosity=verbosity,
    )
    if _in_jupyter():
        from IPython.display import Video

        return Video(
            str(output_path),
            embed=True,
            html_attributes="controls autoplay loop muted",
        )
    return None