SliceStack#

class voxel.SliceStack(tensor, geometry=None, labels=None)#

A multi-channel stack of image slices with a world-space representation.

The slice stack tensor has dimensions \((C, N, X, Y)\) where \(C\) is the number of feature channels, \(N\) is the number of slices, and \(X, Y\) are the in-plane dimensions. Each slice is positioned independently in world space, so the slices need not form a uniform grid.

property geometry: SliceStackGeometry#

The slice stack geometry representing the transformation of each slice from voxel-center coordinates to world-space (or scanner) coordinates.

save(filename, fmt=None) → None#

Save the slice stack to a file.

Parameters:
  • filename (PathLike) – The path to the file to save.

  • fmt (str, optional) – The format of the file. If None, the format is determined by the file extension.

property num_slices: int#

The number of slices (the second slice stack dimension size).

crop(cropping) → SliceStack#

Crop the slice stack with a slicing tuple, which selects slices along the slice dimension and crops within the plane.

Parameters:

cropping (tuple) – Slices over the \((C, N, X, Y)\) dimensions.

Returns:

SliceStack – The cropped slice stack instance.

transform(transform) → SliceStack#

Apply a world-space affine transform to the slice stack. This only moves the slice geometries, never the image data. Deformations are not supported.

Parameters:

transform (AffineMatrix) – Transform to apply.

Returns:

SliceStack – Transformed slice stack.

split(angle=1.0, gap=2.0, coverage=True) → list[SliceStack]#

Split the slice stack into uniform blocks that can each be treated as a volume. A block holds slices on parallel planes with no large gap between neighbors, sorted by position along the block normal.

Parameters:
  • angle (float, optional) – Maximum angle in degrees between the normal of a slice and the normal of the first slice of its block. If None, slices of any orientation are grouped.

  • gap (float, optional) – A block is cut between neighboring slices whose distance exceeds 1 + gap times a reference length. If None, blocks are never cut.

  • coverage (bool, optional) – If True, the reference length is the slice thickness, so gap measures the space left uncovered between slices in units of thickness. Otherwise it is the median slice distance.

Returns:

list of SliceStack – The slice stack blocks.

sample(points, mode='linear', fill=0, angle=1.0, gap=2.0, coverage=True) → Tensor#

Sample slice stack features at a set of world-space points. Each block of slices (see split) is sampled as a volume, in which the slice coordinate of a point follows the positions of the two slices that bracket it. Points covered by multiple blocks take the mean across blocks, or the first block with nearest sampling.

Parameters:
  • points (Tensor) – World coordinates of shape \((..., 3)\).

  • mode (str, optional) – The sampling mode, either ‘linear’ or ‘nearest’.

  • fill (float, optional) – Value of points not covered by any slice.

  • angle (float, optional) – Maximum normal angle within a block.

  • gap (float, optional) – Maximum relative gap within a block.

  • coverage (bool, optional) – Whether the gap is relative to slice thickness.

Returns:

Tensor – The sampled features, with shape \((..., C)\).

resample_like(target, mode='linear', fill=0, angle=1.0, gap=2.0, coverage=True) → Volume#

Resample the slice stack features into the geometry of a target volume. See sample for how the slices are interpolated. A slice stack whose slices form a regular grid is resampled as a volume.

Parameters:
  • target (Volume or VolumeGeometry) – Target volume geometry.

  • mode (str, optional) – Interpolation mode, either ‘linear’ or ‘nearest’.

  • fill (float, optional) – Value of voxels not covered by any slice.

  • angle (float, optional) – Maximum normal angle within a block.

  • gap (float, optional) – Maximum relative gap within a block.

  • coverage (bool, optional) – Whether the gap is relative to slice thickness.

Returns:

Volume – Resampled volume instance.

as_volume(spacing='min', mode='linear', fill=0, preserve_tilt=False, angle=1.0, gap=2.0, coverage=True) → Volume#

Resample the slice stack into a single volume that covers every slice. The volume grid is aligned with the largest block of slices (see split).

Parameters:
  • spacing (str or float, optional) – Slice spacing of the volume, either a value or the ‘min’, ‘median’, or ‘max’ slice distance of the block.

  • mode (str, optional) – Interpolation mode, either ‘linear’ or ‘nearest’.

  • fill (float, optional) – Value of voxels not covered by any slice.

  • preserve_tilt (bool, optional) – If True, a tilted block is kept as a sheared volume instead of resampled onto an orthogonal grid.

  • angle (float, optional) – Maximum normal angle within a block.

  • gap (float, optional) – Maximum relative gap within a block.

  • coverage (bool, optional) – Whether the gap is relative to slice thickness.

Returns:

Volume – Volume of shape \((C, X, Y, N)\).

abs() → SpatialImage#

Compute absolute values of the image features.

Returns:

SpatialImage – A new image instance.

all(dim=None) → SpatialImage | Tensor#

Check if all elements in the image are True.

Parameters:

dim (int, optional) – The dimension or dimensions to reduce. If None, all dimensions are reduced. If the dimension is 0 (channel axis), a single-channel image is returned.

Returns:

Tensor or SpatialImage – The all-True value(s) or image.

any(dim=None) → SpatialImage | Tensor#

Check if any elements in the image are True.

Parameters:

dim (int, optional) – The dimension or dimensions to reduce. If None, all dimensions are reduced. If the dimension is 0 (channel axis), a single-channel image is returned.

Returns:

Tensor or SpatialImage – The any-True value(s) or image.

apply(func) → SpatialImage#

Apply a function to the image tensor and return a new instance.

Parameters:

func (callable) – The function to apply.

Returns:

SpatialImage – A new image instance.

argmax(dim=None) → SpatialImage | Tensor#

Get the maximum index in the image tensor.

Parameters:

dim (int, optional) – The dimension or dimensions to reduce. If None, all dimensions are reduced. If the dimension is 0 (channel axis), a single-channel image is returned.

Returns:

Tensor or SpatialImage – The maximum indices or image.

property baseshape: Size#

The 3D shape of the image, excluding channel dimension.

bool() → SpatialImage#

Convert the image tensor to boolean data type.

Returns:

SpatialImage – A new boolean image instance.

ceil() → SpatialImage#

Apply the ceil operation to the image features.

Returns:

SpatialImage – A new ceiled image instance.

clamp(min=None, max=None, inplace=False) → SpatialImage#

Clamp the values in the image tensor.

Parameters:
  • min (float, optional) – Minimum value to clamp to.

  • max (float, optional) – Maximum value to clamp to.

  • inplace (bool) – Whether to perform the operation in-place.

Returns:

SpatialImage – A new (if not in-place) clamped image instance.

collapse(labels=None, background=False) → SpatialImage#

Collapse a multi-channel (one-hot or probabilistic) image into a single channel label map. This is the inverse of onehot.

The channel axis is reduced with an argmax, and the resulting per-voxel channel index is optionally recoded into label values.

Parameters:
  • labels (Tensor or LabelLookup, optional) – The label values that the channels correspond to. If None, the channel indices are returned directly. If a tensor or lookup, the channel index is recoded into the corresponding label value.

  • background (bool, optional) – When labels is provided, treat the first channel as the background label 0 (unless already present).

Returns:

SpatialImage – A single-channel label map image.

copy() → SpatialImage#

Copy the image instance. Only the data tensor is copied, not the underlying geometry.

cpu() → SpatialImage#

Move the image tensor to the CPU.

Returns:

SpatialImage – A new image instance with the tensor on the CPU.

cuda() → SpatialImage#

Move the image tensor to the GPU.

Returns:

SpatialImage – A new image instance with the tensor on the GPU.

detach() → SpatialImage#

Detach the image tensor from the current computational graph.

Returns:

SpatialImage – A new image instance with the detached tensor.

property device: device#

Device of the image tensor.

property dtype: dtype#

Datatype of the image tensor.

exp() → SpatialImage#

Compute exponential of the elements in the image features.

Returns:

SpatialImage – A new exponentiated image instance.

float() → SpatialImage#

Convert the image tensor to float data type.

Returns:

SpatialImage – A new float image instance.

floor() → SpatialImage#

Apply the floor operation to the image features.

Returns:

SpatialImage – A new floored image instance.

full_like(fill, channels=None, dtype=None) → SpatialImage#

Create an image filled with a specific value and with the same geometry and device as the current instance.

Parameters:
  • fill (float) – The fill value.

  • channels (int, optional) – Number of channels in the new image. If None, will default to the existing number.

  • dtype (torch.dtype, optional) – Target data type.

Returns:

SpatialImage – A new filled image instance.

half() → SpatialImage#

Convert the image tensor to half-precision float data type.

Returns:

SpatialImage – A new half-precision float image instance.

int() → SpatialImage#

Convert the image tensor to integer data type.

Returns:

SpatialImage – A new integer image instance.

isin(elements) → SpatialImage#

Tests if each element of elements is in the image.

Parameters:

elements (Tensor or Scalar) – Values against which to test each voxel.

Returns:

SpatialImage –

A boolean image that is True when a voxel value is

in elements and False otherwise.

isnan() → SpatialImage#

Compute a mask of NaN values in the image.

Returns:

SpatialImage – A new image mask instance.

property labels: LabelLookup | None#

The label lookup table annotating the integer values of this image, or None if the image has no associated labels.

log() → SpatialImage#

Compute the natural logarithm of the image features.

Returns:

SpatialImage – A new log-transformed image instance.

max(dim=None) → SpatialImage | Tensor#

Get the maximum value in the image tensor.

Parameters:

dim (int, optional) – The dimension or dimensions to reduce. If None, all dimensions are reduced. If the dimension is 0 (channel axis), a single-channel image is returned.

Returns:

Tensor or SpatialImage – The maximum value(s) or image.

maximum(other) → SpatialImage#

Computes the element-wise maximum between two images.

Parameters:

other (SpatialImage) – The input image to compare against.

Returns:

SpatialImage – A maximized image instance.

mean(dim=None) → SpatialImage | Tensor#

Compute the mean of all voxels.

Parameters:

dim (int, optional) – The dimension or dimensions to reduce. If None, all dimensions are reduced. If the dimension is 0 (channel axis), a single-channel image is returned.

Returns:

Tensor or SpatialImage – The mean value(s) or image.

min(dim=None) → SpatialImage | Tensor#

Get the minimum value in the image features.

Parameters:

dim (int, optional) – The dimension or dimensions to reduce. If None, all dimensions are reduced. If the dimension is 0 (channel axis), a single-channel image is returned.

Returns:

Tensor or SpatialImage – The mininum value(s) or image.

minimum(other) → SpatialImage#

Computes the element-wise minimum between two images.

Parameters:

other (SpatialImage) – The input image to compare against.

Returns:

SpatialImage – A minimized image instance.

new(tensor, geometry=None, keep_labels=True) → SpatialImage#

Construct a new image instance with the provided features tensor, while preserving any unchanged properties of the original image.

Parameters:
  • tensor (Tensor) – The new image tensor replacement.

  • geometry (VolumeGeometry or SliceStackGeometry, optional) – The new geometry. If None, the current geometry will be propagated.

  • keep_labels (bool, optional) – Whether to propagate the current label lookup table to the new image. Should be False for operations that no longer produce an integer label map.

property num_channels: int#

The number of feature channels (the first image dimension size).

onehot(labels=-1, background=False) → SpatialImage#

One hot encode a label image, with one channel per class.

Parameters:
  • labels (int or Tensor or LabelLookup, optional) – The classes to encode. If an integer, it is the total number of classes (with -1 inferring one greater than the largest voxel value). If a tensor or lookup of label values, the image is first recoded so those values map to the one-hot channels, in order.

  • background (bool, optional) – When labels is a tensor or lookup, reserve the first channel for the background label 0 (unless already present).

Returns:

SpatialImage – The one-hot encoded image.

ones_like(channels=None, dtype=None) → SpatialImage#

Create an image of ones with the same geometry and device as the current instance.

Parameters:
  • channels (int, optional) – Number of channels in the new image. If None, will default to the existing number.

  • dtype (torch.dtype, optional) – Target data type.

Returns:

SpatialImage – A new image instance filled with ones.

pow(exponent) → SpatialImage#

Compute the power of the image features.

Parameters:

exponent (float) – The exponent value.

Returns:

SpatialImage – A new powered image instance.

quantile(q) → Tensor#

Compute the q-th quantile of the voxel data.

Parameters:

q (float) – A scalar quantile in the range [0, 1].

Returns:

Tensor – The quantile scalar value.

rand_like(channels=None, dtype=None) → SpatialImage#

Create an image of random values with the same geometry and device as the current instance. Values are sampled from a uniform distribution on the interval [0, 1).

Parameters:
  • channels (int, optional) – Number of channels in the new image. If None, will default to the existing number.

  • dtype (torch.dtype, optional) – Target data type.

Returns:

SpatialImage – A new random image instance.

randn_like(channels=None, dtype=None) → SpatialImage#

Create an image of random values with the same geometry and device as the current instance. Values are sampled from a normal distribution with mean 0 and variance 1

Parameters:
  • channels (int, optional) – Number of channels in the new image. If None, will default to the existing number.

  • dtype (torch.dtype, optional) – Target data type.

Returns:

SpatialImage – A new random image instance.

recode(mapping, reverse=False, background=False) → SpatialImage#

Remap the integer label values of the image via a lookup.

In the forward direction, the image is treated as an index map and each voxel value i is replaced with mapping[i]. In the reverse direction, each voxel value is replaced with its position in mapping (the inverse operation).

A LabelLookup is treated as its ordered integer indices. When the forward direction is used with a LabelLookup, the recoded voxel values are the real label values it describes, so the lookup is attached to the returned image as its labels.

Parameters:
  • mapping (LabelLookup or Tensor or list) – The ordered values to map index positions to.

  • reverse (bool, optional) – Map values back to their index positions.

  • background (bool, optional) – Prepend the background label 0 to mapping (unless already present) so it occupies the first index.

Returns:

SpatialImage – A new label-map image with remapped values.

property shape: Size#

The 4D shape of the image, including channel dimension.

softmax(dim=0) → SpatialImage | Tensor#

Apply a softmax along a dimension of the image tensor.

Parameters:

dim (int, optional) – The dimension along which to apply the softmax. Defaults to the channel axis (0), in which case an image is returned.

Returns:

Tensor or SpatialImage – Softmaxed probabilities.

split_into_volumes(spacing='min', mode='linear', fill=0, preserve_tilt=False, angle=1.0, gap=2.0, coverage=True) → list[Volume]#

Split the slice stack into blocks and resample each into its own volume. See split and as_volume.

Parameters:
  • spacing (str or float, optional) – Slice spacing of each volume, either a value or the ‘min’, ‘median’, or ‘max’ slice distance of its block.

  • mode (str, optional) – Interpolation mode, either ‘linear’ or ‘nearest’.

  • fill (float, optional) – Value of voxels not covered by any slice.

  • preserve_tilt (bool, optional) – If True, a tilted block is kept as a sheared volume instead of resampled onto an orthogonal grid.

  • angle (float, optional) – Maximum normal angle within a block.

  • gap (float, optional) – Maximum relative gap within a block.

  • coverage (bool, optional) – Whether the gap is relative to slice thickness.

Returns:

list of Volume – One volume per block.

sqrt() → SpatialImage#

Compute the square root of the image features.

Returns:

SpatialImage – A new square-rooted image instance.

square() → SpatialImage#

Compute the square of the image features.

Returns:

SpatialImage – A new squared image instance.

sum(dim=None) → SpatialImage | Tensor#

Compute the sum of all voxels.

Parameters:

dim (int, optional) – The dimension or dimensions to reduce. If None, all dimensions are reduced. If the dimension is 0 (channel axis), a single-channel image is returned.

Returns:

Tensor or SpatialImage – The summed value(s) or image.

property tensor: Tensor#

The image feature tensor, always 4D with a leading channel dimension.

to(device) → SpatialImage#

Move the image tensor to a device.

Parameters:

device (device) – The target device.

Returns:

SpatialImage – A new image instance with the tensor on the target device.

type(dtype) → SpatialImage#

Convert the image tensor to a specified data type.

Parameters:

dtype (torch.dtype) – The target data type.

Returns:

SpatialImage – A new image instance.

unique(**kwargs) → Tensor#

Compute the unique elements of image.

Parameters:

**kwargs (Any) – Additional arguments passed to the underlying call to torch.unique().

Returns:

Tensor – The output list of unique scalar elements.

zeros_like(channels=None, dtype=None) → SpatialImage#

Create an image of zeros with the same geometry and device as the current instance.

Parameters:
  • channels (int, optional) – Number of channels in the new image. If None, will default to the existing number.

  • dtype (torch.dtype, optional) – Target data type.

Returns:

SpatialImage – A new image instance filled with zeros.