surfa.Slice#

class surfa.Slice(data, geometry=None, labels=None, metadata=None)#

2D image class defining an array with data frames and associated geometry.

Parameters
  • data (array_like) – Image data array.

  • geometry (ImageGeometry, optional) – Image geometry mapping the image data to world coordinates.

  • labels (dict or LabelLookup, optional) – Label-name lookup for segmentation indices.

  • metadata (dict, optional) – Dictionary containing arbitrary array metadata.

Attributes

basedim

Base spatial dimensionality of the array (always excludes frame dimension).

baseshape

Base spatial shape of the data array (always excludes the frame dimension).

data

Core data numpy ndarray.

dtype

Data type.

framed_data

Core data array reshaped to include the frame dimension, regardless of nframes.

geom

Linear relationship between image coordinates and world-space coordinates.

labels

Label-name lookup for segmentation indices.

metadata

Dictionary to store various metadata associated with the image.

nframes

Number of data frames.

shape

True shape of the internal data array.

size

Total number of elements in the data array.

Methods

astype(dtype, copy=True, order='K')#

Copy of the array, casted to a specified type.

Parameters
  • dtype (np.dtype) – Target datatype.

  • copy (bool) – Return copy if array already has matching datatype.

  • order ({‘C’, ‘F’, ‘A’, ‘K’}) – Controls the memory layout order of the result. ‘C’ means C order, ‘F’ means Fortran order, ‘A’ means ‘F’ order if all the arrays are Fortran contiguous, ‘C’ order otherwise, and ‘K’ means as close to the order the array elements appear in memory as possible.

Returns

arr – Array with target datatype.

Return type

Slice

barycenters(labels=None, space='image')#

Compute barycenters of the image data. If labels are not provided, the barycenter of each full image frame are returned.

Parameters
  • labels (int or array of int) – Label values to compute barycenters for.

  • space (Space) – Coordinate space of computed barycenters.

Returns

points – Barycenter points. If $L$ labels are specified, the output will be of shape $(L, D)$, where $D$ is the dimension of the image. If the number of image frames $F$ is greater than one, the barycenter array will be of shape $(F, L, D)$.

Return type

array of float

bbox(margin=None)#

Compute the bounding box of the image data greater than zero. If the image has more than one frame, the bounding box will be computed across all frames.

Parameters

margin (int of sequence of int) – Add a margin to the bounding box in units of voxels. The margin will not extend beyond the base image shape.

Returns

Bounding box as an index expression.

Return type

tuple of slice

ceil()#

Ceil the array to integer values.

clip(a_min, a_max)#

Clip the array between low and high values.

Parameters
  • a_min (array_like or None) – Minimum and maximum value. If None, clipping is not performed on the corresponding edge

  • a_max (array_like or None) – Minimum and maximum value. If None, clipping is not performed on the corresponding edge

collapse(mapping=None)#

Collapse a one-hot encoded probabilistic map to discrete labels.

Parameters

mapping (array_like of int) – List of label indices that correspond to probabilistic data frames encoded.

Returns

arr – Collapsed, discrete segmentation array.

Return type

Slice

conform(shape=None, voxsize=None, orientation=None, dtype=None, method='linear', copy=True)#

Conforms image to a specific shape, type, resolution, and orientation.

Parameters
  • shape (tuple of int) – Target shape.

  • voxsize (scalar or float) – Voxel size in millimeters.

  • orientation (str) – Case-insensitive orientation string.

  • method ({'linear', 'nearest'}) – Image interpolation method if resample is enabled.

  • dtype (np.dtype) – Target datatype.

  • copy (bool) – Return copy of image even if requirements are already satisfied.

Returns

arr – Conformed image.

Return type

Slice

connected_component_mask(k=1, fill=False)#

Compute a mask corresponding to the top $k$ largest connected components in the image data.

Parameters
  • k (int) – Top $k$ largest connected components to include in the mask.

  • fill (bool) – Binary fill all holes in the computed mask.

Returns

masks – Binary mask of the connected component.

Return type

Slice

connected_components()#

Find all connected components in the image data.

Returns

components – Label map of all individual connected components. The order of these labels is arbitrary.

Return type

Slice

copy()#

Return a deep copy of the object.

crop_to_bbox(margin=None, crop_like=None)#

Crop to the bounding box of image data greater than zero.

Parameters
  • margin (int of sequence of int) – Add a margin to the bounding box in units of voxels. The margin will not extend beyond the base image shape.

  • crop_like (list of FramedImages) – A list of volumes that will be cropped to the same bounding box as self

Returns

cropped – Cropped image with updated geometry.

Return type

Slice

dilate(steps, kernel=None, mask=None)#

Dilate binary image data.

Parameters
  • steps (int) – Number of dilation steps.

  • kernel (array) – Dilation kernel.

  • mask (array) – Mask to apply dilation to.

Returns

dilated

Return type

Image

distance()#

Compute the distance transform representing distances outside the binary object.

See also

signed_distance

Compute the signed distance transform.

Returns

sdt

Return type

Slice

erode(steps, kernel=None, mask=None)#

Erode binary image data.

Parameters
  • steps (int) – Number of erosion steps.

  • kernel (array) – Erosion kernel.

  • mask (array) – Mask to apply erosion to.

Returns

eroded

Return type

Image

fit_to_shape(shape, center=None, copy=True)#

This is an alias to reshape() for backwards compatability.

Parameters
  • shape (tuple of int) – Target shape.

  • center (center type) – This is a legacy argument that will be ignored.

  • copy (bool) – Return copy of image even if target shape is already satisfied.

Returns

arr – Reshaped image.

Return type

Slice

floor()#

Floor the array to integer values.

max(frames=False)#

Compute the maximum.

Parameters

frames (bool) – Compute max along frame axis.

Returns

Returns scalar max value, unless frames=True, in which case a new Slice is returned.

Return type

scalar or Slice

mean(nonzero=False, frames=False)#

Compute the mean.

Parameters
  • nonzero (bool) – If enabled, only consider nonzero elements. This is ignored if frames=True.

  • frames (bool) – Compute mean along frame axis.

Returns

Returns scalar mean value, unless frames is set to true, in which case a new Slice is returned.

Return type

scalar or Slice

min(nonzero=False, frames=False)#

Compute the minimum.

Parameters
  • nonzero (bool) – If enabled, only consider nonzero elements. This is ignored if frames=True.

  • frames (bool) – Compute min along frame axis.

Returns

Returns scalar min value, unless frames is set to true, in which case a new Slice is returned.

Return type

scalar or Slice

new(data, geometry=None)#

Return a new instance of the array with updated data. Metadata and geometry is preserved unless specified.

onehot(mapping, dtype=<class 'numpy.int32'>)#

Convert discrete labels to a one-hot encoded probabilistic map.

Parameters
  • mapping (array_like of int) – List of label indices to one-hot encode. Label order is preserved.

  • dtype (np.dtype) – Output segmentation datatype.

Returns

arr – Multi-frame one-hot segmentation array.

Return type

Slice

percentile(percentiles, method='linear', nonzero=False)#

Compute the q-th percentile of the data.

Parameters
  • percentiles (array_like of float) – Percentile or sequence of percentiles to compute, which must be between 0 and 100 inclusive.

  • method (str) – Method to use for estimating the percentile. View numpy percentile doc for more information.

  • nonzero (bool) – If enabled, only consider nonzero elements.

Returns

percentile – Computes percentiles.

Return type

scalar or ndarray

reorient(orientation, copy=True)#

Realigns image data and world matrix to conform to a specific slice orientation.

Parameters
  • orientation (str) – Case-insensitive orientation string.

  • copy (bool) – Return copy of image even if target orientation is already satisfied.

Returns

arr – Reoriented image.

Return type

Slice

resample_like(target, method='linear', copy=True, fill=0)#

Resample to a specified target image geometry.

Parameters
  • target (ImageGeometry) – Target image geometry to resample image data into.

  • method ({'linear', 'nearest'}) – Image interpolation method.

  • copy (bool) – Return copy of image even if target voxel size is already satisfied.

  • fill (scalar) – Fill value for out-of-bounds voxels.

Returns

resampled – Resampled image with updated geometry.

Return type

Slice

reshape(shape, copy=True)#

Returns a volume fit to a given shape. Image will be centered in the conformed volume.

Parameters
  • shape (tuple of int) – Target shape.

  • copy (bool) – Return copy of image even if target shape is already satisfied.

Returns

arr – Reshaped image.

Return type

Slice

resize(voxsize, method='linear', copy=True)#

Reslice image to a specified voxel size.

Parameters
  • voxsize (scalar or float) – Voxel size in millimeters.

  • method ({'linear', 'nearest'}) – Image interpolation method.

  • copy (bool) – Return copy of image even if target voxel size is already satisfied.

Returns

resized – Resized image with updated geometry.

Return type

Slice

round()#

Round the array to the nearest integer value.

sample(points, method='linear', bounds_error=False, fill=None)#

Interpolate values from the image grid at particular voxel coordinates.

Parameters
  • points ((m, n) float) – Array of m voxel coordinates to sample values from in the n-D image domain.

  • method ({'linear', 'nearest'}) – Image interpolation method.

  • bounds_error (bool) – Raise error if interpolated values are requested outside of the domain of the input data.

  • fill (number) – If provided, the value to use for points outside of the interpolation domain. If None, values outside the domain are extrapolated.

Returns

sampled – Interpolated data points at each coordinate location in the image domain. Result will be 2 dimensional if multiple frames are present in the source image.

Return type

(m,) or (m, f) array

save(filename, fmt=None, intent=0)#

Write array to file.

Parameters
  • filename (str) – Target filename to write array to.

  • fmt (str) – Optional file format to force.

signed_distance()#

Compute the signed distance transform of the binary image. Negative values represent distances inside the binary object, and positive values represent distances outside the object.

See also

signed_distance

Compute the distance transform outside the binary object.

Returns

sdt

Return type

Slice

smooth(sigma)#

Smooth with Gaussian filter.

Parameters

sigma (sigmascalar or sequence of scalars) – Standard deviation in mm for Gaussian kernel.

Returns

smoothed – Smoothed image.

Return type

Slice

transform(trf=None, method='linear', rotation='corner', resample=True, fill=0)#

Apply an affine or non-linear transform.

**The original implementation has been moved to Affine.transform and Warp.transform. **The method is now impemeted to transform image using Affine.transform and Warp.transform.

Note on trf argument: It accepts Affine/Warp object, or deformation fields (4D numpy array). Pass trf argument as a numpy array is deprecated and will be removed in the future. It is assumed that the deformation fields represent a displacement vector field in voxel space. So under the hood, images will be moved into the space of the deformation field if the image geometries differ.

Parameters
  • trf (Affine/Warp or Slice) – Affine transform or nonlinear deformation (displacement) to apply to the image.

  • method ({'linear', 'nearest'}) – Image interpolation method if resample is enabled.

  • rotation ({'corner', 'center'}) – Apply affine with rotation axis at the image corner or center.

  • resample (bool) – If enabled, voxel data will be interpolated and resampled, and geometry will be set the target. If disabled, voxel data will not be modified, and only the geometry will be updated (this is not possible if a displacement field is provided).

  • fill (scalar) – Fill value for out-of-bounds voxels.

Returns

arr – Transformed image.

Return type

Slice

unique()#

Find all unique elements of an array, sorted.

zeros(dtype=None, frames=None, order='K')#

Return a copy of the framed array with all elements set to zero.

Parameters
  • dtype (np.dtype) – Data type of new array.

  • frames (int) – Number of frames to allocate. If None, the number of frames is determined from the source array.

  • order ({‘C’, ‘F’, ‘K’}) – Controls the memory layout order of the result. ‘C’ means C order, ‘F’ means Fortran order, and ‘K’ means as close to the order the array elements appear in memory as possible.

Returns

arr – Array with zero values.

Return type

Slice