Volume¶
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).
Parameters:
-
tensor(Tensor) –Image data tensor of shape \((C, W, H, D)\) or \((W, H, D)\).
-
geometry(AcquisitionGeometry or AffineMatrix, default:None) –Affine geometry or matrix representing the voxel-to-world coordinate transform. If None, it defaults to a shifted identity in which the image volume is centered at the world origin.
-
labels(LabelLookup, default:None) –A lookup table annotating the integer values of a label-mapped volume with names and colors.
geometry: vx.AcquisitionGeometry
property
writable
¶
The acquisition geometry representing the transformation from voxel-center coordinates to world-space (or scanner) coordinates.
labels: vx.LabelLookup | None
property
writable
¶
The label lookup table annotating the integer values of this volume, or None if the volume has no associated labels.
tensor: torch.Tensor
property
¶
The volume feature tensor, always of shape \((C, W, H, D)\).
shape: torch.Size
property
¶
The 4D \((C, W, H, D)\) shape of the volume, including channel dimension.
baseshape: torch.Size
property
¶
The spatial 3D \((W, H, D)\) shape of the volume, excluding channel dimension.
num_channels: int
property
¶
The number of feature channels (the first volume dimension size).
device: torch.device
property
¶
Device of the volume tensor.
dtype: torch.dtype
property
¶
Datatype of the volume tensor.
new(tensor, geometry=None, keep_labels=True) -> Volume
¶
Construct a new volume instance with the provided features tensor, while preserving any unchanged properties of the original volume.
Parameters:
-
tensor(Tensor) –The new image tensor replacement.
-
geometry(AcquisitionGeometry, default:None) –The new geometry. If None, the current geometry will be propagated.
-
keep_labels(bool, default:True) –Whether to propagate the current label lookup table to the new volume. Should be False for operations that no longer produce an integer label map.
copy() -> Volume
¶
Copy the volume instance. Only the data tensor is copied, not the underlying geometry.
save(filename, fmt=None) -> None
¶
Save the volume to a file.
Parameters:
-
filename(PathLike) –The path to the file to save.
-
fmt(str, default:None) –The format of the file. If None, the format is determined by the file extension.
apply(func) -> Volume
¶
Apply a function to the volume tensor and return a new instance.
Parameters:
-
func(callable) –The function to apply.
Returns:
-
Volume–A new volume instance.
detach() -> Volume
¶
Detach the volume tensor from the current computational graph.
Returns:
-
Volume–A new volume instance with the detached tensor.
to(device) -> Volume
¶
cuda() -> Volume
¶
Move the volume tensor to the GPU.
Returns:
-
Volume–A new volume instance with the tensor on the GPU.
cpu() -> Volume
¶
Move the volume tensor to the CPU.
Returns:
-
Volume–A new volume instance with the tensor on the CPU.
type(dtype) -> Volume
¶
Convert the volume tensor to a specified data type.
Parameters:
-
dtype(dtype) –The target data type.
Returns:
-
Volume–A new volume instance.
float() -> Volume
¶
half() -> Volume
¶
Convert the volume tensor to half-precision float data type.
Returns:
-
Volume–A new half-precision float volume instance.
int() -> Volume
¶
bool() -> Volume
¶
max(dim=None) -> Volume | torch.Tensor
¶
min(dim=None) -> Volume | torch.Tensor
¶
sum(dim=None) -> Volume | torch.Tensor
¶
mean(dim=None) -> Volume | torch.Tensor
¶
floor() -> Volume
¶
ceil() -> Volume
¶
abs() -> Volume
¶
exp() -> Volume
¶
Compute exponential of the elements in the volume features.
Returns:
-
Volume–A new exponentiated volume instance.
log() -> Volume
¶
Compute the natural logarithm of the volume features.
Returns:
-
Volume–A new log-transformed volume instance.
sqrt() -> Volume
¶
Compute the square root of the volume features.
Returns:
-
Volume–A new square-rooted volume instance.
square() -> Volume
¶
pow(exponent) -> Volume
¶
isnan() -> Volume
¶
clamp(min=None, max=None, inplace=False) -> Volume
¶
Clamp the values in the volume tensor.
Parameters:
-
min(float, default:None) –Minimum value to clamp to.
-
max(float, default:None) –Maximum value to clamp to.
-
inplace(bool, default:False) –Whether to perform the operation in-place.
Returns:
-
Volume–A new (if not in-place) clamped volume instance.
maximum(other) -> Volume
¶
minimum(other) -> Volume
¶
all(dim=None) -> Volume | torch.Tensor
¶
any(dim=None) -> Volume | torch.Tensor
¶
zeros_like(channels=None, dtype=None) -> Volume
¶
Create a volume of zeros with the same geometry and device as the current instance.
Parameters:
-
channels(int, default:None) –Number of channels in the new volume. If None, will default to the existing number.
-
dtype(dtype, default:None) –Target data type.
Returns:
-
Volume–A new volume instance filled with zeros.
ones_like(channels=None, dtype=None) -> Volume
¶
Create a volume of ones with the same geometry and device as the current instance.
Parameters:
-
channels(int, default:None) –Number of channels in the new volume. If None, will default to the existing number.
-
dtype(dtype, default:None) –Target data type.
Returns:
-
Volume–A new volume instance filled with ones.
full_like(fill, channels=None, dtype=None) -> Volume
¶
Create a volume filled with a specific value and with the same geometry and device as the current instance.
Parameters:
-
fill(float) –The fill value.
-
channels(int, default:None) –Number of channels in the new volume. If None, will default to the existing number.
-
dtype(dtype, default:None) –Target data type.
Returns:
-
Volume–A new filled volume instance.
rand_like(channels=None, dtype=None) -> Volume
¶
Create a volume 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, default:None) –Number of channels in the new volume. If None, will default to the existing number.
-
dtype(dtype, default:None) –Target data type.
Returns:
-
Volume–A new random volume instance.
randn_like(channels=None, dtype=None) -> Volume
¶
Create a volume 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, default:None) –Number of channels in the new volume. If None, will default to the existing number.
-
dtype(dtype, default:None) –Target data type.
Returns:
-
Volume–A new random volume instance.
isin(elements) -> Volume
¶
Tests if each element of elements is in the volume.
Parameters:
-
elements(Tensor or Scalar) –Values against which to test each voxel.
Returns:
-
Volume–A boolean volume that is True when a voxel value is in
elementsand False otherwise.
unique(**kwargs) -> torch.Tensor
¶
Compute the unique elements of volume.
Parameters:
-
**kwargs(Any, default:{}) –Additional arguments passed to the underlying call to
torch.unique().
Returns:
-
Tensor–The output list of unique scalar elements.
quantile(q) -> torch.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.
softmax(dim=0) -> Volume | torch.Tensor
¶
argmax(dim=None) -> Volume | torch.Tensor
¶
recode(mapping, reverse=False, background=False) -> vx.Volume
¶
Remap the integer label values of the volume via a lookup.
In the forward direction, the volume 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 volume as its labels.
Parameters:
-
mapping(LabelLookup or Tensor or list) –The ordered values to map index positions to.
-
reverse(bool, default:False) –Map values back to their index positions.
-
background(bool, default:False) –Prepend the background label 0 to
mapping(unless already present) so it occupies the first index.
Returns:
-
Volume–A new label-map volume with remapped values.
onehot(labels=-1, background=False) -> vx.Volume
¶
One hot encode a label volume, with one channel per class.
Parameters:
-
labels(int or Tensor or LabelLookup, default:-1) –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 volume is first recoded so those values map to the one-hot channels, in order.
-
background(bool, default:False) –When
labelsis a tensor or lookup, reserve the first channel for the background label 0 (unless already present).
Returns:
-
Volume–The one-hot encoded volume.
collapse(labels=None, background=False) -> vx.Volume
¶
Collapse a multi-channel (one-hot or probabilistic) volume 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, default:None) –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, default:False) –When
labelsis provided, treat the first channel as the background label 0 (unless already present).
Returns:
-
Volume–A single-channel label map volume.
sample(points, space, mode='linear', padding_mode='zeros') -> torch.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, default:'linear') –The sampling mode, either 'linear' or 'nearest'.
-
padding_mode(str, default:'zeros') –Padding mode for outside grid values.
Returns:
-
Tensor–The sampled features, with shape \((..., C)\).
tesselate(threshold=0.5, space='world') -> vx.Mesh
¶
Tesselate a mesh around connected voxel components. This is not differentiable.
Parameters:
-
threshold(float, default:0.5) –Scalar threshold that determines whether a voxel is inside or outside the mesh boundary.
-
space(Space, default:'world') –The coordinate space of mesh vertices. Default is the world coordinate space.
Returns:
-
Mesh–Tesselated mesh.
bounds(nonzero=False, margin=None, space='world') -> vx.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, default:False) –If True, compute the bounds around all non-zero voxels, otherwise use the extent of the image grid.
-
margin(float or Tensor, default:None) –Margin to expand the bounds. Can be a positive or negative delta.
-
space(Space, default:'world') –Space of the margin values, either 'voxel' or 'world'.
Returns:
-
BoundingBox–Bounding box in world-space coordinates.
centroids(space) -> torch.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, default:None) –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, default:'world') –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, default:None) –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, default:()) –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.
Parameters:
-
target(Volume | AcquisitionGeometry) –Target acquisition geometry.
-
mode(str, default:'linear') –Interpolation mode.
-
padding_mode(str, default:'zeros') –Padding mode for outside grid values.
-
fill(float, default:0) –Out of bounds value used for fill padding mode.
-
antialias(bool or float, default:False) –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, default:None) –Target voxel spacing. An isotropic target is assumed if a scalar is provided.
-
*components(float, default:()) –Additional components of
spacing, allowing values to be passed as separate positional arguments, e.g.resample(1, 1, 2). -
in_plane_spacing(float | Tensor, default:None) –Target in-plane voxel spacing. Mutually exclusive with the
spacingargument. -
slice_spacing(float | Tensor, default:None) –Target slice spacing. Mutually exclusive except with the
spacingargument. -
mode(str, default:'linear') –Interpolation mode.
-
padding_mode(str, default:'zeros') –Padding mode for outside grid values.
-
antialias(bool or float, default:False) –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) -> 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, default:()) –Additional components of
baseshape, allowing values to be passed as separate positional arguments, e.g.reshape(64, 64, 64).
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, default:()) –Additional components of
delta, allowing values to be passed as separate positional arguments, e.g.pad(1, 2, 3, 'voxel'). -
space(Space, default:None) –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, default:()) –Additional components of
delta, allowing values to be passed as separate positional arguments, e.g.trim(1, 2, 3, 'voxel'). -
space(Space, default:None) –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, resample=None, mode='linear', padding_mode='zeros') -> Volume
¶
Apply a spatial transform to the volume. Affine matrices are assumed to be world-space transforms. By default an affine only moves the world geometry without touching the image data, while a warp always resamples and pins the result to the warp grid domain.
Parameters:
-
transform(AffineMatrix or Warp) –Transform to apply.
-
resample(bool, default:None) –If True, the image data is resampled on its grid. If None, resampling defaults to False for affine inputs and True for warps. Cannot be False for warps.
-
mode(str, default:'linear') –Interpolation mode if resampling.
-
padding_mode(str, default:'zeros') –Padding mode for outside grid values if resampling.
Returns:
-
Volume–Transformed volume.
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, default:2) –The size of the pooling window. Defaults to 2.
-
*components(int, default:()) –Additional components of
scale, allowing values to be passed as separate positional arguments, e.g.pool(2, 2, 1). -
mode(str, default:'mean') –Pooling mode - can be 'mean' or 'max'. Defaults to 'mean'.
-
space(Space, default:None) –Space of the scale value. Can be provided as the last positional argument. Defaults to 'voxel'.
-
spacing_ratio_thresh(float, default:None) –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, default:()) –Additional components of
sigma, allowing values to be passed as separate positional arguments, e.g.smooth(1, 1, 2). -
space(Space, default:None) –The space of the sigma values, either 'voxel' or 'world'. Can be provided as the last positional argument. Defaults to 'world'.
-
truncate(float, default:2) –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, default:1) –Number of dilation iterations.
-
connectivity(int, default:1) –Neighborhood connectivity between 1 and 3.
-
iso_thresh(float, default:None) –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, default:1) –Number of erosion iterations.
-
connectivity(int, default:1) –Neighborhood connectivity between 1 and 3.
-
iso_thresh(float, default:None) –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, default:1) –Number of dilation and erosion iterations.
-
connectivity(int, default:1) –Neighborhood connectivity between 1 and 3.
-
iso_thresh(float, default:None) –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, default:1) –Number of erosion and dilation iterations.
-
connectivity(int, default:1) –Neighborhood connectivity between 1 and 3.
-
iso_thresh(float, default:None) –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).