API

class SimpleITK.utilities.Logger(logger: ~logging.Logger = <Logger SimpleITK (WARNING)>)

Adapts SimpleITK messages to be handled by a Python Logger object.

Allows using the logging module to control the handling of messages coming from ITK and SimpleTK. Messages such as debug and warnings are handled by objects derived from sitk.LoggerBase.

The LoggerBase.SetAsGlobalITKLogger method must be called to enable SimpleITK messages to use the logger.

The Python logger module adds a second layer of control for the logging level in addition to the controls already in SimpleITK.

The “Debug” property of a SimpleITK object must be enabled (if available) and the support from the Python “logging flow” hierarchy to handle debug messages from a SimpleITK object.

Warning messages from SimpleITK are globally disabled with ProcessObject:GlobalWarningDisplayOff.

DisplayDebugText(LoggerBase self, char const * t)
DisplayErrorText(LoggerBase self, char const * t)
DisplayGenericOutputText(LoggerBase self, char const * t)
DisplayText(LoggerBase self, char const * t)
DisplayWarningText(LoggerBase self, char const * t)
SimpleITK.utilities.fft_based_translation_initialization(fixed: Image, moving: Image, *, required_fraction_of_overlapping_pixels: float = 0.0, initial_transform: Transform = None, masked_pixel_value: float = None) TranslationTransform

Perform fast Fourier transform based normalized correlation to find the translation which maximizes correlation between the images.

If the moving image grid is not congruent with fixed image ( same origin, spacing and direction ), then it will be resampled onto the grid defined by the fixed image.

Efficiency can be improved by reducing the resolution of the image or using a projection filter to reduce the dimensionality of the inputs.

Parameters:
  • fixed – A SimpleITK image object.

  • moving – Another SimpleITK Image object, which will be resampled onto the grid of the fixed image if it is not congruent.

  • required_fraction_of_overlapping_pixels – The required fraction of overlapping pixels between the fixed and moving image. The value should be in the range of [0, 1]. If the value is 1, then the full overlap is required.

  • initial_transform – An initial transformation to be applied to the moving image by resampling before the FFT registration. The returned transform will be of the initial_transform type with the translation updated.

  • masked_pixel_value – The value of input pixels to be ignored by correlation. If None, then the FFTNormalizedCoorrelation will be used, otherwise the MaskedFFTNormalizedCorrelation will be used.

Returns:

A TranslationTransform (or the initial_transform tyype) mapping physical points from the fixed to the moving image.

SimpleITK.utilities.make_isotropic(image, interpolator=2, spacing=None, default_value=0, standardize_axes=False)

Many file formats (e.g. jpg, png,…) expect the pixels to be isotropic, same spacing for all axes. Saving non-isotropic data in these formats will result in distorted images. This function makes an image isotropic via resampling, if needed.

Parameters:
  • image (SimpleITK.Image) – (SimpleITK.Image): Input image.

  • interpolator – By default the function uses a linear interpolator. For label images one should use the sitkNearestNeighbor interpolator so as not to introduce non-existent labels.

  • spacing (float) – Desired spacing. If none given then use the smallest spacing from the original image.

  • default_value – Desired pixel value for resampled points that fall outside the original image (e.g. HU value for air, -1000, when image is CT).

  • standardize_axes (bool) – If the original image axes were not the standard ones, i.e. non identity cosine matrix, we may want to resample it to have standard axes. To do that, set this parameter to True.

Returns:

An image with isotropic spacing which occupies the same region in space as the input image.

Return type:

SimpleITK.Image

SimpleITK.utilities.overlay_bounding_boxes(image: Image, bounding_boxes: Sequence[Sequence[float]], bounding_box_format: str = 'MINXY_MAXXY', normalized: bool = False, colors: Sequence[int] = [], half_line_width: int = 0) Tuple[Image, bool]

Overlay axis aligned bounding boxes on a 2D image. The function supports several ways of specifying a bounding box using pixel indexes:

  1. “MINXY_MAXXY” - [min_x, min_y, max_x, max_y]

  2. “MINXY_WH” - [min_x, min_y, width, height]

  3. “CENT_WH” - [center_x, center_y, width, height]

  4. “CENT_HALFWH” - [center_x, center_y, width/2, height/2]

Bounding boxes are plotted in the order they appear in the iterable/list. To change the overlap between rectangles change the order in the list. The last entry in the list will be plotted on top of the previous ones.

Caveat: When using larger line widths, bounding boxes that are very close to the image border may cause an exception and result in partial overlay. A trivial solution is to decrease the value of the half_line_width parameter.

Parameters:
  • image – Input image, 2D image with scalar or RGB pixels on which we plot the bounding boxes.

  • bounding_boxes – Bounding boxes to plot. Each bounding box is represented by four numbers.

  • bounding_box_format – One of [“MINXY_MAXXY”, “MINXY_WH”, “CENT_WH”, “CENT_HALFWH”] specifying the meaning of

the four entries representing the bounding box. :param normalized: Indicate whether the bounding box numbers were normalized to be in [0,1]. :param colors: Specify the color for each rectangle using RGB values, triplets in [0,255]. Useful for visually representing different classes (relevant for object detection). Most often a flat list, e.g. colors = [255, 0, 0, 0, 255, 0] reresents red, and green. :param half_line_width: Plot using thicker lines. :return: A tuple where the first entry is a SimpleITK image with rectangles plotted on it and the second entry is a boolean which is true if one or more of the rectangles were out of bounds, false otherwise.

SimpleITK.utilities.resize(image: Image, new_size: Sequence[int], isotropic: bool = True, fill: bool = True, interpolator=2, fill_value: float = 0.0, use_nearest_extrapolator: bool = False, anti_aliasing_sigma: None | float | Sequence[float] = None) Image

Resize an image to an arbitrary size while retaining the original image’s spatial location.

Allows for specification of the target image size in pixels, and whether the image pixels spacing should be isotropic. The physical extent of the image’s data is retained in the new image, with the new image’s spacing adjusted to achieve the desired size. The image is centered in the new image.

Anti-aliasing is enabled by default.

Runtime performance can be increased by disabling anti-aliasing ( anti_aliasing_sigma=0 ), and by setting the interpolator to sitkNearestNeighbor at the cost of decreasing image quality.

Parameters:
  • image – A SimpleITK image.

  • new_size – The new image size in pixels.

  • isotropic – If False, the original image is resized to fill the new image size by adjusting space. If True,

the new image’s spacing will be isotropic. :param fill: If True, the output image will be new_size, and the original image will be centered in the new image with constant or nearest values used to fill in the new image. If False and isotropic is True, the output image’s new size will be calculated to fit the original image’s extent such that at least one dimension is equal to new_size. :param fill_value: Value used for padding. :param interpolator: Interpolator used for resampling. :param use_nearest_extrapolator: If True, use a nearest neighbor for extrapolation when resampling, overridding the constant fill value. :param anti_aliasing_sigma: If zero no antialiasing is performed. If a scalar, it is used as the sigma value in

physical units for all axes. If None or a sequence, the sigma value for each axis is calculated as $sigma = (new_spacing - old_spacing) / 2$ in physical units. Gaussian smoothing is performed prior to resampling for antialiasing.

Returns:

A SimpleITK image with desired size.

SimpleITK.utilities.slice_by_slice(func)

A function decorator which executes func on each 3D sub-volume and in-place pastes the results into the input image. The input image type and the output image type are required to be the same type.

Parameters:

func – A function which takes a SimpleITK Image as it’s first

argument and returns an Image as the result.

Returns:

A decorated function.

SimpleITK.utilities.dask.from_sitk(filename: str | Path, chunks: int | Tuple = None) Array

Reads the filename into a dask array with map_block.

SimpleITK is used to “stream read” chunks from the file if supported, otherwise the entire image will be read for each chunk request.ITK support full streaming includes MHA, MRC, NRRD and NIFTI file formats.

Parameters:
  • filename – A path-like object to the location of an image file readable by SimpleITK.

  • chunks – Please see dask documentation on chunks of dask arrays for supported formats. Chunk size can be tuned for performance based on continuously stored on disk, re-chunking, and downstream processes.

Returns:

A Dask array of the image on file.

SimpleITK.utilities.vtk.sitk2vtk(image: Image) vtkImageData

Convert a 2D or 3D SimpleITK image to a VTK image.

VTK versions prior to version 9 do not support a direction cosine matrix. If the installed version is lower than that, the direction cosine matrix is ignored and that information is lost. A warning is issued using the Python logging mechanism.

VTK images are fundamentally 3D, so 2D images are made 3D with a Z dimension of 1.

Parameters:

image – Image to convert.

Returns:

A VTK image.

SimpleITK.utilities.vtk.vtk2sitk(image: vtkImageData) Image

Convert a VTK image to a SimpleITK image.

Note that VTK images are fundamentally 3D, even if the Z dimension is 1.

Parameters:

image – Image to convert.

Returns:

A SimpleITK image.