Volume#

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

A multi-channel volumetric (3D) image with a world-space representation.

The volume grid has dimensions \((C, W, H, D)\) where \(C\) is the number of feature channels and \(W, H, D\) are the spatial width, height, and depth of the image (called the baseshape).

property geometry: VolumeGeometry#

The acquisition geometry representing the transformation from voxel-center coordinates to world-space (or scanner) coordinates.

save(filename, fmt=None) → None#

Save the volume 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.

sample(points, space, mode='linear', padding_mode='zeros') → Tensor#

Sample volume features at a set of points.

Parameters:
  • points (Tensor | Mesh) – A set of points in world, voxel, or local grid sampling coordinates with shape \((..., 3)\). If the input is a mesh, the vertex positions are used.

  • space (Space) – The coordinate space of the input points or mesh.

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

  • padding_mode (str, optional) – Padding mode for outside grid values.

Returns:

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

tesselate(threshold=0.5, space='world') → Mesh#

Tesselate a mesh around connected voxel components. This is not differentiable.

Parameters:
  • threshold (float, optional) – Scalar threshold that determines whether a voxel is inside or outside the mesh boundary.

  • space (Space, optional) – The coordinate space of mesh vertices. Default is the world coordinate space.

Returns:

Mesh – Tesselated mesh.

bounds(nonzero=False, margin=None, space='world') → BoundingBox#

Compute a world-space bounding box enclosing the volume grid or the non-zero voxels in the image. The box covers the full extent of the voxels, i.e. it is padded 0.5 voxels beyond the outermost voxel centers.

Parameters:
  • nonzero (bool) – If True, compute the bounds around all non-zero voxels, otherwise use the extent of the image grid.

  • margin (float or Tensor, optional) – Margin to expand the bounds. Can be a positive or negative delta.

  • space (Space, optional) – Space of the margin values, either ‘voxel’ or ‘world’.

Returns:

BoundingBox – Bounding box in world-space coordinates.

centroids(space) → Tensor#

Compute the centroids (centers of mass) for each volume channel. All negative values are clamped to zero before computing the centroids.

Parameters:

space (Space) – The coordinate space of computed centroids.

Returns:

Tensor – Per-channel coordinates of shape (C, 3).

slice(point, direction, space) → Volume#

Extract a slice from the volume. Note this will still return a volume, but with a slice dimension reduced to 1.

Parameters:
  • point (int or Tensor) – A point of the slice plane. If a tensor, it should represent a 3D point coordinate. If an int, it should be the index of the slice in the specified direction. Note that this requires the slice direction axis to be specified as an int as well.

  • direction (int or Tensor) – The direction of the slice plane. If a tensor, it should represent a 3D vector direction. If an int, it should be the index of the slice in the specified direction.

  • space (Space) – The coordinate space of the slice point and direction.

Returns:

Volume – The sliced volume instance.

crop(cropping, margin=None, space='world') → Volume#

Crop the volume to some bounding, either defined by a voxel slicing tuple or a world-space bounding box.

Parameters:
  • cropping (tuple or BoundingBox) – Cropping defined by either a tuple of slices or a bounding box.

  • margin (float or Tensor, optional) – Margin to expand the cropping boundary. Can be a positive or negative delta. The boundary will be clipped if it extends beyond the shape of the volume.

  • space (Space) – The coordinate space of the margin values, either ‘voxel’ or ‘world’.

Returns:

Volume – The cropped volume instance.

crop_to_nonzero(margin=None, *components) → Volume#

Crop the volume to the bounding box around nonzero voxels.

Parameters:
  • margin (float or Tensor, optional) – Margin (in world units) to expand the cropping boundary. Can be a positive or negative delta. The boundary will be clipped if it extends beyond the shape of the volume.

  • *components (float) – Additional components of margin, allowing values to be passed as separate positional arguments, e.g. crop_to_nonzero(1, 1, 2).

Returns:

Volume – The cropped volume instance.

reorient(orientation) → Volume#

Transform the volume to a new orientation. This is faster than achieving the same result through resampling.

Parameters:

orientation (Orientation) – The target orientation.

Returns:

Volume – The reoriented volume instance.

resample_like(target, mode='linear', padding_mode='zeros', fill=0, antialias=False) → Volume#

Resample the volume features to match the geometry of a target volume. On CUDA devices with Triton available, interpolation runs in a grid-free kernel.

Parameters:
  • target (Volume | VolumeGeometry) – Target acquisition geometry.

  • mode (str, optional) – Interpolation mode.

  • padding_mode (str, optional) – Padding mode for outside grid values.

  • fill (float, optional) – Out of bounds value used for fill padding mode.

  • antialias (bool or float, optional) – If True, will apply a Gaussian filter before resampling to avoid aliasing artifacts, with a standard deviation of a third of the downsampling factor. A float sets that proportion instead.

Returns:

Volume – Resampled volume instance.

resample(spacing=None, *components, in_plane_spacing=None, slice_spacing=None, mode='linear', padding_mode='zeros', antialias=False) → Volume#

Resample voxel features to a new voxel grid spacing.

Parameters:
  • spacing (float | Tensor) – Target voxel spacing. An isotropic target is assumed if a scalar is provided.

  • *components (float) – Additional components of spacing, allowing values to be passed as separate positional arguments, e.g. resample(1, 1, 2).

  • in_plane_spacing (float | Tensor) – Target in-plane voxel spacing. Mutually exclusive with the spacing argument.

  • slice_spacing (float | Tensor) – Target slice spacing. Mutually exclusive except with the spacing argument.

  • mode (str, optional) – Interpolation mode.

  • padding_mode (str, optional) – Padding mode for outside grid values.

  • antialias (bool or float, optional) – If True, will apply a Gaussian filter before resampling to avoid aliasing artifacts, with a standard deviation of a third of the downsampling factor. A float sets that proportion instead.

Returns:

Volume – Volume resampled to the target voxel spacing.

reshape(baseshape, *components, stretch=False, mode=None, antialias=False) → Volume#

Modify the spatial extent of the volume, cropping or padding around the center image to fit a given baseshape.

This method is symmetric in that performing a reverse reshape operation will always yield the original geometry.

Parameters:
  • baseshape (int | Size) – Target spatial (3D) shape. An isotropic shape is assumed if a scalar is provided.

  • *components (int) – Additional components of baseshape, allowing values to be passed as separate positional arguments, e.g. reshape(64, 64, 64).

  • stretch (bool, optional) – If True, the image is stretched (or squashed) to the target shape by interpolation instead of cropped or padded, i.e. the world-space extent is preserved and the voxel spacing is rescaled along each axis.

  • mode (str, optional) – Interpolation mode. Defaults to ‘nearest’ when cropping or padding (which is exact) and ‘linear’ when stretch is True.

  • antialias (bool or float, optional) – If True, will apply a Gaussian filter before resampling to avoid aliasing artifacts when downsampling with stretch. See resample_like for details.

Returns:

Volume – Reshaped volume instance.

pad(delta, *components, space=None) → Volume#

Pad the spatial extent of the volume by a given delta. Note that a negative delta value will result in trimming (cropping).

Parameters:
  • delta (float or Tensor) – Delta of specified units to pad (or crop) the volume by in each direction. Can be of size \((1,)\), \((3,)\), or \((3, 2)\).

  • *components (float) – Additional components of delta, allowing values to be passed as separate positional arguments, e.g. pad(1, 2, 3, 'voxel').

  • space (Space) – The coordinate space of the delta values, either ‘voxel’ or ‘world’. Can be provided as the last positional argument.

Returns:

Volume – Padded volume instance.

trim(delta, *components, space=None) → Volume#

Trim the spatial extent of the volume by a given delta. This is equivalent to padding with negative delta values.

Parameters:
  • delta (float or Tensor) – Delta of specified units to trim the volume by in each direction. Can be of size \((1,)\), \((3,)\), or \((3, 2)\).

  • *components (float) – Additional components of delta, allowing values to be passed as separate positional arguments, e.g. trim(1, 2, 3, 'voxel').

  • space (Space) – The coordinate space of the delta values, either ‘voxel’ or ‘world’. Can be provided as the last positional argument.

Returns:

Volume – Trimmed volume instance.

transform(transform, mode='linear', padding_mode='zeros', like=None) → Volume#

Apply a spatial transform to the volume. Affine matrices are world-space transforms and only move the acquisition geometry, never the image data. Warps resample the data and pin the result to the warp grid. A displacement field (or the forward field of a pair) is applied as a warp on this volume’s own grid, so the result keeps its geometry (the field is sampled there, with zero displacement beyond its extent). A transform series is condensed first, to at most one affine followed by one deformation, so the data is interpolated once. With like, the result is resampled onto that geometry instead, still with a single interpolation: an affine result is resampled after the move, and a deformation is sampled on that grid.

Parameters:
  • transform (AnyTransform) – Transform to apply.

  • mode (str, optional) – Interpolation mode when resampling.

  • padding_mode (str, optional) – Padding mode for outside grid values when resampling.

  • like (Volume or VolumeGeometry, optional) – Geometry the result is resampled onto. By default an affine moves the geometry, a field keeps it, and a warp imposes its own.

Returns:

Volume – Transformed volume.

as_slice_stack(direction=None) → SliceStack#

Convert the volume to a slice stack without interpolation.

Parameters:

direction (int, optional) – Voxel dimension to slice along. Defaults to the slice direction of the geometry.

Returns:

SliceStack – Slice stack of shape \((C, N, X, Y)\).

pool(scale=2, *components, mode='mean', space=None, spacing_ratio_thresh=None) → Volume#

Pool the voxel data with a sliding window.

By default, this will pool over all dimensions, but it can be conditionally disabled for the slice dimension based on the ratio of slice vs in-plane spacing, i.e. the value of geometry.spacing_ratio. For example, if the slice spacing is spacing_ratio_thresh times greater than the in-plane spacing, the slice dimension will not be pooled. Mind that if the resulting pooled volume has a slice spacing less than the in-plane spacing, it will be resampled to an isotropic resolution.

There is no analogous unpool method because there is complexity in determining the desired unpooling strategy. To return to the original geometry, instead use the resample_like method. If no reference geometry is available, just use the reshape method to upsample.

Note that this implementation must mirror the pooling operation used by the geometry class. Any changes to the pooling operation in one class must be reflected in the other.

Parameters:
  • scale (int, optional) – The size of the pooling window. Defaults to 2.

  • *components (int) – Additional components of scale, allowing values to be passed as separate positional arguments, e.g. pool(2, 2, 1).

  • mode (str, optional) – Pooling mode - can be ‘mean’ or ‘max’. Defaults to ‘mean’.

  • space (Space, optional) – Space of the scale value. Can be provided as the last positional argument. Defaults to ‘voxel’.

  • spacing_ratio_thresh (float, optional) – Slice spacing ratio that determines whether the slice dimension is pooled. This is disabled by default.

Returns:

Volume – Pooled volume.

smooth(sigma, *components, space=None, truncate=2) → Volume#

Apply Gaussian smoothing to the image features.

Parameters:
  • sigma (float | Tensor) – Smoothing sigma.

  • *components (float) – Additional components of sigma, allowing values to be passed as separate positional arguments, e.g. smooth(1, 1, 2).

  • space (Space, optional) – The space of the sigma values, either ‘voxel’ or ‘world’. Can be provided as the last positional argument. Defaults to ‘world’.

  • truncate (float, optional) – The number of standard deviations to extend the kernel before truncating.

Returns:

Volume – Smoothed volume.

dilate(iterations=1, connectivity=1, iso_thresh=None) → Volume#

Apply a binary dilation to the nonzero voxels of the volume.

Parameters:
  • iterations (int, optional) – Number of dilation iterations.

  • connectivity (int, optional) – Neighborhood connectivity between 1 and 3.

  • iso_thresh (float, optional) – Spacing ratio at or above which the operation is applied only in-plane. Disabled by default.

Returns:

Volume – Dilated volume of the same data type.

erode(iterations=1, connectivity=1, iso_thresh=None) → Volume#

Apply a binary erosion to the nonzero voxels of the volume.

Parameters:
  • iterations (int, optional) – Number of erosion iterations.

  • connectivity (int, optional) – Neighborhood connectivity between 1 and 3.

  • iso_thresh (float, optional) – Spacing ratio at or above which the operation is applied only in-plane. Disabled by default.

Returns:

Volume – Eroded volume of the same data type.

close(iterations=1, connectivity=1, iso_thresh=None) → Volume#

Apply a binary closing (dilation followed by erosion) to the nonzero voxels of the volume.

Parameters:
  • iterations (int, optional) – Number of dilation and erosion iterations.

  • connectivity (int, optional) – Neighborhood connectivity between 1 and 3.

  • iso_thresh (float, optional) – Spacing ratio at or above which the operation is applied only in-plane. Disabled by default.

Returns:

Volume – Closed volume of the same data type.

open(iterations=1, connectivity=1, iso_thresh=None) → Volume#

Apply a binary opening (erosion followed by dilation) to the nonzero voxels of the volume.

Parameters:
  • iterations (int, optional) – Number of erosion and dilation iterations.

  • connectivity (int, optional) – Neighborhood connectivity between 1 and 3.

  • iso_thresh (float, optional) – Spacing ratio at or above which the operation is applied only in-plane. Disabled by default.

Returns:

Volume – Opened volume of the same data type.

show(**kwargs) → None#

Show the volume in a Monocle viewer window. This is a convenience method for vx.monocle.show(volume).

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.

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.