Skip to content

Reorient

Bases: SpatialTransform

Reorder voxel axes to match a target orientation.

The voxels are permuted and/or flipped so that the image axes align with the specified anatomical directions. The affine matrix is updated to preserve the physical positions of the voxels.

Common orientation codes:

  • 'RAS': Left→\ R\ ight, Posterior→\ A\ nterior, Inferior→\ S\ uperior.
  • 'LPS': Right→\ L\ eft, Anterior→\ P\ osterior, Inferior→\ S\ uperior.

See the NiBabel docs on image orientation <https://nipy.org/nibabel/image_orientation.html>__ for details.

Parameters:

Name Type Description Default
orientation str

Target three-letter orientation code. Must contain one letter for each axis pair: R/L, A/P, S/I.

'RAS'
**kwargs Any

See Transform for additional keyword arguments.

{}

Examples:

>>> import torchio as tio
>>> transform = tio.Reorient()            # default: RAS
>>> transform = tio.Reorient(orientation='LPS')
>>> transform = tio.Reorient(orientation='SPL')
Source code in src/torchio/transforms/spatial/reorient.py
class Reorient(SpatialTransform):
    r"""Reorder voxel axes to match a target orientation.

    The voxels are permuted and/or flipped so that the image axes
    align with the specified anatomical directions. The affine matrix
    is updated to preserve the physical positions of the voxels.

    Common orientation codes:

    - `'RAS'`: Left→\ **R**\ ight,
      Posterior→\ **A**\ nterior, Inferior→\ **S**\ uperior.
    - `'LPS'`: Right→\ **L**\ eft,
      Anterior→\ **P**\ osterior, Inferior→\ **S**\ uperior.

    See the `NiBabel docs on image orientation
    <https://nipy.org/nibabel/image_orientation.html>`__ for details.

    Args:
        orientation: Target three-letter orientation code. Must
            contain one letter for each axis pair: R/L, A/P, S/I.
        **kwargs: See [`Transform`][torchio.Transform] for additional
            keyword arguments.

    Examples:
        >>> import torchio as tio
        >>> transform = tio.Reorient()            # default: RAS
        >>> transform = tio.Reorient(orientation='LPS')
        >>> transform = tio.Reorient(orientation='SPL')
    """

    def __init__(
        self,
        orientation: str = "RAS",
        **kwargs: Any,
    ) -> None:
        super().__init__(**kwargs)
        self.orientation = _validate_orientation(orientation)

    def make_params(self, batch: SubjectsBatch) -> dict[str, Any]:
        first_images = next(iter(batch.images.values()))
        affine_np = first_images.affines[0].numpy()
        current_codes = "".join(
            nib.orientations.aff2axcodes(affine_np),
        )
        ornt = _compute_reorientation(affine_np, self.orientation)
        return {
            "ornt": ornt.tolist(),
            "original_orientation": current_codes,
        }

    def apply_transform(
        self,
        batch: SubjectsBatch,
        params: dict[str, Any],
    ) -> SubjectsBatch:
        ornt = np.asarray(params["ornt"])

        # No-op when already in target orientation
        is_identity = np.array_equal(ornt[:, 0], [0, 1, 2]) and np.all(ornt[:, 1] == 1)
        if is_identity:
            return batch

        for _name, img_batch in self._get_images(batch).items():
            original_shape = img_batch.data.shape[-3:]
            img_batch.data = _apply_reorientation(img_batch.data, ornt)

            for affine in img_batch.affines:
                inv_aff = orientations.inv_ornt_aff(ornt, original_shape)
                new_matrix = affine.numpy() @ inv_aff
                affine._matrix = torch.as_tensor(
                    new_matrix,
                    dtype=torch.float64,
                )

        return batch

    @property
    def invertible(self) -> bool:
        return True

    def inverse(self, params: dict[str, Any]) -> Reorient:
        """Inverse reorients back to the original orientation."""
        return Reorient(
            orientation=params["original_orientation"],
            copy=False,
        )

supports_per_instance_params property

Whether this transform can sample parameters per batch element.

Defaults to False. Transforms that implement per-instance parameter sampling override this to return True. When False, the transform always uses batch-shared parameters regardless of the per_instance flag, preserving the legacy behavior.

supports_per_instance_p property

Whether this transform can gate each batch element independently.

Defaults to False. Shape-preserving transforms that implement per-element probability override this to return True. Shape-changing transforms must leave it False because masked and unmasked elements would have incompatible shapes.

forward(data)

forward(data: Subject) -> Subject
forward(data: Image) -> Image
forward(data: Tensor) -> Tensor
forward(data: np.ndarray) -> np.ndarray
forward(data: sitk.Image) -> sitk.Image
forward(data: nib.Nifti1Image) -> nib.Nifti1Image
forward(data: dict) -> dict
forward(data: ImagesBatch) -> ImagesBatch
forward(data: SubjectsBatch) -> SubjectsBatch

Apply the transform.

The output type always matches the input type.

Parameters:

Name Type Description Default
data Any

Input data to transform.

required
Source code in src/torchio/transforms/transform.py
def forward(self, data: Any) -> Any:
    """Apply the transform.

    The output type always matches the input type.

    Args:
        data: Input data to transform.
    """
    if self.copy:
        data = _copy.deepcopy(data)
    batch, unwrap = self._wrap(data)
    # When per-element gating is active, the transform handles the
    # probability itself (masked-out elements get identity params),
    # so skip the batch-wide coin flip here. Apply iff rand < p, so
    # p=0 is always a no-op and p=1 always applies.
    if not self._per_instance_p_active(batch) and torch.rand(1).item() >= self.p:
        return unwrap(batch)
    params = self.make_params(batch)
    batch = self.apply_transform(batch, params)
    # Record history on the batch, unless every element was gated out by
    # per-element probability: that is an exact no-op, and recording it
    # would let history replay (e.g. an invertible spatial transform)
    # trigger an unnecessary identity resample.
    if not _all_elements_gated_out(params):
        trace = AppliedTransform(name=type(self).__name__, params=params)
        if not hasattr(batch, "applied_transforms"):
            batch.applied_transforms = []
        batch.applied_transforms.append(trace)
    result = unwrap(batch)
    # Propagate history to outputs that can carry it
    if (
        hasattr(batch, "applied_transforms")
        and not isinstance(result, (SubjectsBatch, Tensor, np.ndarray))
        and not isinstance(result, dict)
    ):
        with contextlib.suppress(AttributeError):
            result.applied_transforms = list(batch.applied_transforms)
    return result

to_hydra()

Export as a Hydra-compatible config dict.

Returns a dict with _target_ set to the fully qualified class name and only non-default field values included.

Returns:

Type Description
dict[str, Any]

Dict suitable for hydra.utils.instantiate().

Source code in src/torchio/transforms/transform.py
def to_hydra(self) -> dict[str, Any]:
    """Export as a Hydra-compatible config dict.

    Returns a dict with `_target_` set to the fully qualified
    class name and only non-default field values included.

    Returns:
        Dict suitable for `hydra.utils.instantiate()`.
    """
    from .parameter_range import _ParameterRange

    cls = type(self)
    target = f"torchio.{cls.__qualname__}"
    cfg: dict[str, Any] = {"_target_": target}

    for name, default in _collect_init_params(cls).items():
        value = getattr(self, name, default)
        if isinstance(value, _ParameterRange):
            if value._original == default:
                continue
            value = _hydra_value(value._original)
        elif value == default:
            continue
        else:
            value = _hydra_value(value)
        cfg[name] = value
    return cfg

inverse(params)

Inverse reorients back to the original orientation.

Source code in src/torchio/transforms/spatial/reorient.py
def inverse(self, params: dict[str, Any]) -> Reorient:
    """Inverse reorients back to the original orientation."""
    return Reorient(
        orientation=params["original_orientation"],
        copy=False,
    )