skrt.image module

Classes for loading and comparing medical images.

class skrt.image.Image(path='', load=True, title=None, affine=None, voxel_size=(1, 1, 1), origin=(0, 0, 0), nifti_array=False, downsample=None, dtype=None, auto_timestamp=False, default_intensity=(-200, 300), log_level=None, rgb_weights=(0.299, 0.587, 0.114), rgb_rescale_slope=100, rgb_rescale_intercept=0)

Bases: Archive

Class representing a medical image.

Attributes of an Image object should usually be accessed via their getter methods, rather than directly, to ensure that attribute values have been loaded.

__init__(path='', load=True, title=None, affine=None, voxel_size=(1, 1, 1), origin=(0, 0, 0), nifti_array=False, downsample=None, dtype=None, auto_timestamp=False, default_intensity=(-200, 300), log_level=None, rgb_weights=(0.299, 0.587, 0.114), rgb_rescale_slope=100, rgb_rescale_intercept=0)

Initialise from a medical image source.

Parameters:

pathstr/array/Nifti1Image, default = “”

Source of image data. Can be either:

  1. A string, optionally with wildcards, containing the path to one or multiple dicom files, the path to a directory containg dicom files, or the path to a single nifti file;

  2. A list of paths, optionally with wildcards, to dicom files;

  3. A string, optionally containing wildcards, containing the path to a single numpy file containing a 2D or 3D array;

  4. A 2D or 3D numpy array;

  5. A nibabel.nifti1.Nifti1Image object;

  6. An existing Image object to be cloned; in this case, all other input args except <title> will be ignored, as these will be taken from the existing Image.

Notes:

  1. If path points to a single file, all files in the same directory as this file are considered also.

2. When path resolves to multiple dicom files, only files that match the values of the first file for the dicom attributes: “StudyInstanceUID”, “SeriesNumber”, “Modality”, “ImageOrientationPatient”. When path points to a single file in a directory with others, this file is taken as the first file. Otherwise, files are sorted according to natural sort order (so “2.dcm” before “11.dcm”). To load images from files in a single directory (or in a directory tree) that may have different values for these, it could be better to use the skrt.patient.Patient class:

from skrt import Patient p = Patient(“path/to/directory”, unsorted_dicom=True)

For more details, see documentation of Patient class.

loadbool, default=True

If True, the image data will be immediately loaded. Otherwise, it can be loaded later with the load() method.

titlestr, default=None

Title to use when plotting the image. If None and <source> is a path, a title will be automatically generated from the filename.

affine4x4 array, default=None

Array containing the affine matrix to use if <source> is a numpy array or path to a numpy file. If not None, this takes precendence over <voxel_size> and <origin>.

voxel_sizetuple, default=(1, 1, 1)

Voxel sizes in mm in order (x, y, z) to use if <source> is a numpy array or path to a numpy file and <affine> is not provided.

origintuple, default=(0, 0, 0)

Origin position in mm in order (x, y, z) to use if <source> is a numpy array or path to a numpy file and <affine> is not provided.

nifti_arraybool, default=False

If True and <source> is a numpy array or numpy file, the array will be treated as a nifti-style array, i.e. (x, y, z) in (row, column, slice), as opposed to dicom style.

downsampleint/list, default=None

Amount by which to downsample the image. Can be a single value for all axes, or a list containing downsampling amounts in order (x, y, z).

dtypetype, default=None

Type to which loaded data should be cast.

auto_timestampbool default=False

If true and no valid timestamp is found within the path string, timestamp generated from current date and time.

default_intensitytuple,None default=(-200, 300)

Default intensity range for image display. This can be specified as a two-element tuple, giving minimum and maximum, or if set to None then intensity range used is from the minimum of zero and the image minimum, to the image maximum. If WindowCenter and WindowWidth are defined in a DICOM source file, these values will be used instead to define the default intensity range.

log_level: str/int/None, default=None

Severity level for event logging. If the value is None, log_level is set to the value of skrt.core.Defaults().log_level.

add_dose(dose)

Add a Dose object to be associated with this image. This does not affect the image associated with the Dose object.

Parameters:

doseskrt.dose.Dose

A Dose object to assign to this image.

add_plan(plan)

Add a Plan object to be associated with this image. This does not affect the image associated with the Plan object.

Parameters:

planskrt.dose.Plan

A Plan object to assign to this image.

add_sinogram_noise(phi0=60000, eta=185000, verbose=False)

Add Poisson fluctuations at level of sinogram.

For a kV CT scan mapped to the radiodensity scale of an MV CT scan (self.map_hu(‘kv_to_mv’), this function adds intensity fluctuations to reproduce better the fluctuations in an MV CT scan.

The procedure for adding fluctuations was originally devised and implemented by M.Z. Wilson.

Parameters:

phi0int/float, default=60000

Notional photon flux used in image creation.

etaint/float, default=185000

Notional constant of proportionality linking radiodensity and line integrals measuring attenuation along photon paths.

verbosebool, default=False

Print information on progress in noise addition

add_structure_set(structure_set)

Add a structure set to be associated with this image. This does not affect the image associated with the structure set.

Parameters:

structure_setskrt.structures.StructureSet

A StructureSet object to assign to this image.

apply_banding(bands=None)

Apply banding to image data.

Parameter:

bands - dict, default=None

Dictionary of value bandings to be applied to image data. Keys specify band limits, and values indicte the values to be assigned. For example:

  • bands{-100: -1024, 100: 0, 1e10: 1024}

will result in the following banding:

  • value <= -100 => -1024;

  • -100 < value <= 100 => 0;

  • 100 < value <= 1e10 => 1024.

apply_selective_banding(bands=None)

Apply banding to selected intensity ranges of image data.

This is one of two skrt.image.Image methods to perform banding:

  • apply_banding(): assign all intensity values to bands;

  • apply_selective_banding(): assign only selected intensity values to bands.

Both methods accept as input a dictionary specifying bands, but the dictionary format for the two methods is different.

Parameter:

bands - dict, default=None

Dictionary of value bandings to be applied to image data. Keys are floats specifying intensities to be assigned, and values are two-element tuples indicating lower and upper band limits. If the first element is None, no lower limit is applied; if the second element is None, no upper limit is applied. For example:

  • bands{-1024: (None, -100), 1024: (100, None}

will result in the following banding:

  • value <= -100 => -1024;

  • -100 < value <= 100 => original values retained;

  • 100 < value => 1024.

assign_intensity_to_rois(rois=None, intensity=0)

Assign intensity value to image regions corresponding to ROIs.

Parameters:

roislist of skrt.structures.ROI objects, default=None

ROIs for which voxels are to be assigned an intensity value.

intensityint/float, default=0

Intensity value to be assigned to ROI voxels.

assign_structure_set(structure_set)

Assign a structure set to this image.

This does not affect the image associated with the structure set. Any previously assigned structure sets are cleared.

Parameters:

structure_setskrt.structures.StructureSet

A StructureSet object to assign to this image.

astype(itype)

Return image object with requested type of representation.

Image objects loaded from a DICOM source and Image objects loaded from a NIfTI source have different representations for two reasons:

  • indices for an image slice have the order [row][column] in pydicom vs [column][row] in nibabel;

  • axis definitions follow radiology convention in pydicom vs neurology convention in nibabel; for discussion of the conventions, see: https://nipy.org/nibabel/neuro_radio_conventions.html

This function returns the requested representation, independently of the original source.

Parameter:

itypestr

Identifier of the representation type required. Allowed values are ‘dcm’ and ‘dicom’ for a pydicom/DICOM representation; ‘nii’ and ‘nifti’ for a nibabel/NIfTI representation. For any other value, None is returned.

clear_doses()

Clear all dose maps associated with this image.

clear_plans()

Clear all plan maps associated with this image.

clear_structure_sets()

Clear all structure sets associated with this image.

clone_with_structure_set(structure_set=None, roi_names=None, image_structure_set_index=-1, structure_set_name=None)

Clone current image, and associate to clone a filtered structure set.

Parameters:

structure_setskrt.structures.StructureSet, default=None

Structure set to be filtered and associated to image clone. Disregarded if a null value.

roi_namesdict, default=None

Dictionary for renaming and filtering ROIs, where the keys are names for ROIs to be kept, and values are lists of alternative names with which these ROIs may have been labelled. The alternative names can contain wildcards with the ‘*’ symbol. If a value of None is given, all ROIs in the structure set are kept, with no renaming.

image_structure_set_index, int, default=-1

Integer specifying index in current image’s list of structure sets of structure set to be associated with clone. This parameter is considered only if structure_set has a null value.

structure_set_name, str, default=None

Name to be assigned to structure set. If None, existing name is kept.

copy_dicom(outdir='image_dicom', overwrite=True, sort=True, *args, **kwargs)

Copy source dicom files.

Parameters:

outdirpathlib.Path/str, default=”image_dicom”

Path to directory to which source files are to be copied.

overwritebool, default=True

If True, delete and recreate <outdir> before copying files. If False and <outdir> exists already, a file is copied only if this doesn’t mean overwriting an existing file.

sortbool, default=True

If True, copied dicom files will be named by instance number if all files have a different instance number, or else will be numbered sequentially from 1, in order of increasing z-coordinate. If False, files are copied to the output directory with their names unaltered.

argslist

Arguments to be ignored.

kwargsdict

Keyword arguments to be ignored.

crop(xlim=None, ylim=None, zlim=None)

Crop the image to a given x, y, z range in mm. If any are None, the image will not be cropped in that direction.

crop_about_point(point=None, xlim=None, ylim=None, zlim=None)

Crop the image to a given x, y, z range in mm about a point.

If any range is None, the image will not be cropped in that direction.

Parameters:

pointtuple, default=None

(x, y, z) coordinates about which cropping is to be performed. If None, the point (0, 0, 0) is used, and the result will be the same as when calling the Image.crop() method.

xlimtuple, default=None

Lower and upper bounds relative to reference point of cropping along x-axis. If None, cropping is not performed along this axis.

ylimtuple, default=None

Lower and upper bounds relative to reference point of cropping along y-axis. If None, cropping is not performed along this axis.

zlimtuple, default=None

Lower and upper bounds relative to reference point of cropping along z-axis. If None, cropping is not performed along this axis.

crop_by_amounts(dx=None, dy=None, dz=None)

Crop image by the amounts dx, dy, dz in mm.

This method calls the function skrt.image.crop_by_amounts(), with self passed as object for cropping.

The amount of cropping along each direction should be one of: - float : the image is cropped by this amount on both sides; - two-element tuple: the image is cropped on the sides of lower

and higher values by the amounts specified;

  • None : no cropping is performed.

For more details, see documentation of skrt.image.crop_by_amounts().

crop_to_image(image, alignment=None)

Crop to extents of another image, optionally after image alignment.

Parameters:

imageskrt.image.Image

Image to whose extents to perform cropping.

alignmenttuple/dict/str, default=None

Strategy to be used for image alignment prior to cropping. For further details, see documentation of skrt.image.get_alignment_translation().

crop_to_roi(roi, crop_margins=None, crop_about_centre=False, method=None)

Crop image to region defined by an ROI or StructureSet, plus margins.

Parameters:

roisskrt.structures.ROI/skirt.structures.StructureSet

ROI or StructureSet to which image will be cropped.

crop_marginsfloat/tuple, default=None

Float or three-element tuple specifying the margins, in mm, to be added to extents or centre point of ROI or StructureSet. If a float, minus and plus the value specified are added to lower and upper extents respectively along each axis. If a three-element tuple, elements are taken to specify margins in the order (x, y, z). Elements can be either floats (minus and plus the value added respectively to lower and upper extents) or two-element tuples (elements 0 and 1 added respectively to lower and upper extents).

crop_about_centrebool, default=False

If True, image is cropped to the centre point of ROI or StructureSet plus margins. If False, image is cropped to the extents of ROI or StructureSet plus margins.

methodstr, default=None

Method to use for calculating extent of <roi> region. Can be:

  • “contour”: get extent from min/max positions of contour(s).

  • “mask”: get extent from min/max positions of voxels in the binary mask.

  • None: use the method set in self.default_geom_method.

downsample(downsampling)

Apply downsampling to the image array. Can be either a single value (to downsampling equally in all directions) or a list of 3 values.

flattened(view='x-y', combine='sum')

Obtain image flattened across all slices in the specified view. The flattened image is nominally three dimensional. Along the projection axis, the image has a depth of one voxel, and the voxel size is equal to the extent of the original image. The image centre is adjusted such that the extents of the flattened image are the same as those of the original image.

Parameters:

viewstr, default=”x-y”

Orientation; can be “x-y”, “x-z”, “y-x”, “y-z”, “z-x”, or “z-y”.

combinestr, default=”sum”

Name of a numpy function with which to combine array values along an axis, for example “sum”, “max”, “min”, “mean”.

get_affine(standardise=False, force_standardise=True)

Return affine matrix.

Parameters:

standardisebool, default=False

If False, the affine matrix will be returned in the orientation in which it was loaded; otherwise, it will be returned in standard dicom-style orientation such that [column, row, slice] corresponds to the [x, y, z] axes.

get_alignment_translation(other, alignment=None)

Determine translation for aligning <self> to <other>.

This method calls the function of the same name, with <self> and <other> as <im1> and <im2> respectively.

For explanation of parameters, see documentation of skrt.image.get_alignment_translation().

get_axes(col_first=False)

Return list of axis numbers in order [column, row, slice] if col_first is True, otherwise in order [row, column, slice]. The axis numbers 0, 1, and 2 correspond to x, y, and z, respectively.

Parameters:

col_firstbool, default=True

If True, return axis numbers in order [column, row, slice] instead of [row, column, slice].

get_centre()

Get position in mm of the centre of the image.

get_centroid_idx(view='x-y', fraction=1)

Get array index of slice containing centroid of above-threshold voxels.

The centroid coordinate along a given axis is calculated as the unweighted mean of the coordinates of voxels with an intensity at least a given fraction of the maximum.

Parameters:

viewstr, default=”x-y”

Orientation; can be “x-y”, “x-z”, “y-x”, “y-z”, “z-x”, or “z-y”.

fractionfloat, default=1

Minimum fraction of the maximum intensity that a voxel must record to be considered in the centroid calculation.

get_centroid_pos(view='x-y', fraction=1)

Get position of slice containing centroid of above-threshold voxels.

The centroid coordinate along a given axis is calculated as the unweighted mean of the coordinates of voxels with an intensity at least a given fraction of the maximum.

Parameters:

viewstr, default=”x-y”

Orientation; can be “x-y”, “x-z”, “y-x”, “y-z”, “z-x”, or “z-y”.

fractionfloat, default=1

Minimum fraction of the maximum intensity that a voxel must record to be considered in the centroid calculation.

get_centroid_slice(view='x-y', fraction=1)

Get number of slice containing centroid of above-threshold voxels.

The centroid coordinate along a given axis is calculated as the unweighted mean of the coordinates of voxels with an intensity at least a given fraction of the maximum.

Parameters:

viewstr, default=”x-y”

Orientation; can be “x-y”, “x-z”, “y-x”, “y-z”, “z-x”, or “z-y”.

fractionfloat, default=1

Minimum fraction of the maximum intensity that a voxel must record to be considered in the centroid calculation.

get_comparison(other, metrics=None, name=None, name_as_index=True, nice_columns=False, decimal_places=None, base=2, bins=100, xyrange=None)

Return a pandas DataFrame comparing this image with another.

If this image doesn’t have the same shape and geometry as the other image, comparison metrics are evaluated for a clone of this image, resized to match the other.

Parameters:

otherskrt.image.Image

Other image, with which to compare this image.

metricslist, default=None

List of metrics to evaluate. Available metrics:

Calculated in Image.get_mutual_information():

  • “mutual_information”;

  • “normalised_mutual_information”;

  • “information_quality_ratio”;

  • “rajski_distance”.

Calculated in Image.get_quality():

  • “relative_structural_content”;

  • “fidelity”;

  • “correlation_quality”.

If None, defaults to [“mutual_information”]

namestr, default=None

Name identifying comparison. If null, the name is constructed from the titles of the two images compared, as “title1_vs_title2”.

name_as_indexbool, default=True

If True, the index column of the pandas DataFrame will contain the name of this comparison; otherwise, the name will appear in a column labelled “images”.

nice_columnsbool, default=False

If False, column labels will be the same as the input metric names; if True, the names will be capitalized and underscores will be replaced with spaces.

decimal_placesint, default=None

Number of decimal places to keep for each metric. If None, full precision will be used.

baseint/None, default=2

Base to use when taking logarithms, in calculations of mutual information and variants. If None, use base e.

binsint/list, default=50

Numbers of bins to use when histogramming grey-level joint probabilities for self and other, in calculations of mutual information and variants. This is passed as the bins parameter of numpy.histogram2d: https://numpy.org/doc/stable/reference/generated/numpy.histogram2d.html

xyrangelist, default=None

Upper and lower of each axis when histogramming grey-level joint probabilities for self and image, in calculations of mutual informatio and variants. This is passed as the range parameter of numpy.histogram2d: https://numpy.org/doc/stable/reference/generated/numpy.histogram2d.html

get_coordinate_arrays(image_size, origin, voxel_size)

Obtain (x, y, z) arrays of coordinates of voxel centres.

Arrays are useful for image resizing.

Parameters:

image_sizetuple

Image size in voxels, in order (x,y,z).

origintuple

Origin position in mm in order (x, y, z).

voxel_sizetuple

Voxel sizes in mm in order (x, y, z).

get_coords()

Get grids of x, y, and z coordinates for each voxel in the image.

get_correlation_quality(image)

Calculate quality of correlation between this image and another.

Uses method get_quality().

Parameter:

imageskrt.image.Image

Image with respect to which correlation quality is to be calculated. to be evaluated

get_data(standardise=False, force_standardise=True)

Return 3D image array.

Parameters:

standardisebool, default=False

If False, the data array will be returned in the orientation in which it was loaded; otherwise, it will be returned in standard dicom-style orientation such that [column, row, slice] corresponds to the [x, y, z] axes.

get_dicom_array_and_affine(standardise=False)

Get image array and affine matrix in dicom configuration.

get_dicom_dataset(sl=None, idx=None, pos=None)

Return pydicom.dataset.FileDataset object associated with this Image if it was loaded from dicom; otherwise, return None.

If any of <sl>, <idx> or <pos> are provided, the dataset corresponding to that specific slice will be returned; otherwise, the last loaded dataset will be returned.

Parameters:

slint, default=None

Slice number; used if not None.

idxint, default=None

Slice array index; used if not None and <sl> is None.

posfloat, default=None

Slice position in mm; used if not None and <sl> and <idx> are both None.

get_dicom_filepath(sl=None, idx=None, pos=None)

Return path to the dicom dataset corresponding to a specific slice.

Parameters:

slint, default=None

Slice number; used if not None.

idxint, default=None

Slice array index; used if not None and <sl> is None.

posfloat, default=None

Slice position in mm; used if not None and <sl> and <idx> are both None.

get_doses()

Return list of Dose objects associated with this Image.

get_extents()

Get minimum and maximum extent of the image in mm along all three axes, returned in order [x, y, z].

get_fidelity(image)

Calculate fidelity with which this image matches another.

Uses method get_quality().

Parameter:

imageskrt.image.Image

Image with respect to which fidelity is to be calculated. to be evaluated

get_foreground_bbox(threshold=None, convex_hull=False, fill_holes=True, dxy=0)

Obtain bounding box of image foreground.

The bounding box is returned as [(xmin, xmax), (ymin, ymax), (zmin, zmax)], with values in mm.

Method parameters are passed to skrt.image.Image.get_foreground_mask() to obtain a mask defining the image foreground. For parameter explanations, see skrt.image.Image.get_foreground_mask() documentation.

get_foreground_bbox_centre_and_widths(threshold=None, convex_hull=False, fill_holes=True, dxy=0)

Get centre and widths in mm along all three axes of a bounding box enclosing the image foreground. Centre and widths are returned as a tuple ([x, y, z], [dx, dy, dz]).

Method parameters are passed to skrt.image.Image.get_foreground_mask() to obtain a mask defining the image foreground. For parameter explanations, see skrt.image.Image.get_foreground_mask() documentation.

get_foreground_box_mask(dx=0, dy=0, threshold=None)

Slice by slice, create rectangular mask enclosing foreground mask.

dxint, default=0

Margin along columns to be added on each side of mask bounding box.

dyint, default=0

Margin along rows to be added on each side of mask bounding box.

thresholdint/float, default=None

Intensity value above which pixels in a slice are assigned to regions for determination of foreground. If None, use value of Defaults().foreground_threshold. If still None, use Otsu threshold.

get_foreground_comparison(other, name=None, threshold=None, convex_hull=False, fill_holes=True, dxy=0, voxel_size=None, **kwargs)

Return a pandas DataFrame comparing the foregrounds of this image and another.

ROIs obtaining the image foregrounds are obtained, then these are compared using skrt.structures.ROI.get_comparison().

Parameters:

other: skrt.image.Image

Image with which this image is to be compared.

name: str, default=None

Name to be assigned to the ROI representing the foreground of this image, and by default used as row index in DataFrame. If null, the name used is the image title, or if this is null then f”{skrt.core.Defaults().foreground_name}_1” is used.

thresholdint/float, default=None

Intensity value above which pixels in a slice are assigned to regions for determination of foreground. If None, use value of Defaults().foreground_threshold. If still None, use Otsu threshold.

convex_hullbool, default=False

If True, create mask from the convex hulls of the slice foreground masks initially obtained.

fill_holesbool, default=False

If True, fill holes in the slice foreground masks initially obtained.

dxyint, default=0

Margin, in pixel units, to be added to each slice foreground mask.

voxel_sizetuple, default=None

Voxel size (dx, dy, dz) in mm to be used for foreground masks in comparisons. If None, the mask voxel size of <other> is used if not None; otherwise the default voxel size for dummy images, namely (1, 1, 1), is used. If an element of the tuple specifying voxel size is None, the value for the corresponding element of the mask voxel size of <other> is used.

kwargs: dict

Keyword arguments, in addition to voxel_size, passed to skrt.structures.ROI.get_comparison().

get_foreground_mask(threshold=None, convex_hull=False, fill_holes=True, dxy=0)

Create foreground mask.

Slice by slice, the foreground is taken to correspond to the largest region of contiguous pixels above a threshold value.

Parameters:

thresholdint/float, default=None

Intensity value above which pixels in a slice are assigned to regions for determination of foreground. If None, use value of Defaults().foreground_threshold. If still None, use Otsu threshold.

convex_hullbool, default=False

If True, create mask from the convex hulls of the slice foreground masks initially obtained.

fill_holesbool, default=False

If True, fill holes in the slice foreground masks initially obtained.

dxyint, default=0

Margin, in pixel units, to be added to each slice foreground mask.

get_foreground_roi(threshold=None, convex_hull=False, fill_holes=True, dxy=0, **kwargs)

Create ROI represening image foreground.

Slice by slice, the foreground is taken to correspond to the largest region of contiguous pixels above a threshold value. A binary mask representing the foreground is created, and is used as source for creating an ROI.

Parameters:

thresholdint/float, default=None

Intensity value above which pixels in a slice are assigned to regions for determination of foreground. If None, use value of Defaults().foreground_threshold. If still None, use Otsu threshold.

convex_hullbool, default=False

If True, create mask from the convex hulls of the slice foreground masks initially obtained.

fill_holesbool, default=False

If True, fill holes in the slice foreground masks initially obtained.

dxyint, default=0

Margin, in pixel units, to be added to each slice foreground mask.

**kwargs

Keyword arguments passed to ROI constructor.

get_idx(view, sl=None, idx=None, pos=None)

Get an array index from either a slice number, index, or position. If <sl>, <idx>, and <pos> are all None, the index of the central slice of the image in the orienation specified in <view> will be returned.

Parameters:

viewstr

Orientation in which to compute the index. Can be “x-y”, “x-z”, “y-x”, “y-z”, “z-x”, or “z-y”.

slint, default=None

Slice number. If given, this number will be converted to an index and returned.

idxint, default=None

Slice array index. If given and <sl> is None, this index will be returned.

posfloat, default=None

Slice position in mm. If given and <sl> and <idx> are both None, this position will be converted to an index and returned.

get_intensity_mask(vmin=None, vmax=None, convex_hull=False, fill_holes=True, dxy=0)

Create intensity mask.

Slice by slice, the mask corresponds to the largest region of contiguous pixels with intensity values inside a given interval.

Parameters:

vminint/float, default=None

Minimum intensity value for pixel to be included in mask. If None, no constraint on minimum intensity is applied.

vmaxint/float, default=None

Maximum intensity value for pixel to be included in mask. If None, no constraint on maximum intensity is applied.

convex_hullbool, default=False

If True, create mask from the convex hulls of the slice foreground masks initially obtained.

fill_holesbool, default=False

If True, fill holes in the slice foreground masks initially obtained.

dxyint, default=0

Margin, in pixel units, to be added to each slice foreground mask.

get_length(ax='z')

Get total length of image.

get_machine(stations=None)

Return machine name.

Parameter:

machines: dict, default=None

Dictionary mapping between station names and machine names.

get_manufacturer(force=False)

Return the manufacturer of the image-recording device.

The manufacturer will be defined only if the source is DICOM, and the manufacturer is included in the metadata. If the manufacturer is undefined, return an empty string.

Parameter: force: bool, default=False

If True, try to extract the manufactuer from source data, even if already extracted. If False, return any value obtained previously.

get_masked_image(mask=None, mask_threshold=0.5, invert_mask=False)

Return image after application of mask.

maskImage/list/ROI/str/StructureSet, default=None

Image object representing a mask or a source from which an Image object can be initialised. In addition to the sources accepted by the Image constructor, the source may be an ROI, a list of ROIs or a StructureSet. In the latter cases, the mask image is derived from the ROI mask(s).

mask_thresholdfloat, default=0.5

Threshold for mask data. Values above and below this value are set to True and False respectively. Taken into account only if the mask image has non-boolean data.

invert_maskbool, default=False

If True, the mask is inverted before being applied.

get_max(force=False)

Get maximum greyscale value of data array.

get_min(force=False)

Get minimum greyscale value of data array.

get_model(force=False)

Return the model of image-recording device.

The device model will be defined only if the source is DICOM, and the model is included in the metadata. If the model is undefined, return an empty string.

Parameter: force: bool, default=False

If True, try to extract the device model from source data, even if already extracted. If False, return any value obtained previously.

get_mpl_kwargs(view, mpl_kwargs=None, scale_in_mm=True)

Get a dict of kwargs for plotting this image in matplotlib. This will create a default dict, which is updated to contain any kwargs contained in <mpl_kwargs>.

The default parameters are:
  • “aspect”:

    Aspect ratio, set to 1 by default.

  • “extent”:

    Plot extent determined from image geometry.

  • “cmap”:

    Colormap, self._default_cmap by default.

  • “vmin”/”vmax”

    Greyscale range to use; taken from self._default_vmin and self._default_vmax by default.

For information on matplotlib colour maps, see:

https://matplotlib.org/stable/gallery/color/colormap_reference.html

Parameters:

viewstr

Orientation; (any of “x-y”, “x-z”, “y-x”, “y-z”, “z-x”, or “z-y”); needed to compute correct aspect ratio and plot extent.

mpl_kwargsdict, default=None

Dict of kwargs with which to overwrite default kwargs.

scale_in_mmbool, default=True

If True, indicates that image will be plotted with axis scales in mm; needed to compute correct aspect ratio and plot extent.

get_mutual_information(image, base=2, bins=100, xyrange=None, variant='mutual_information')

For this and another image, calculate mutual information or a variant.

The two images considered must have the same shape.

Parameters:

imageskrt.image.Image

Image with respect to which mutual information is calculated.

baseint/None, default=2

Base to use when taking logarithms. If None, use base e.

binsint/list, default=50

Numbers of bins to use when histogramming grey-level joint probabilities for self and image. This is passed as the bins parameter of numpy.histogram2d: https://numpy.org/doc/stable/reference/generated/numpy.histogram2d.html

xyrangelist, default=None

Upper and lower of each axis when histogramming grey-level joint probabilities for self and image. This is passed as the range parameter of numpy.histogram2d: https://numpy.org/doc/stable/reference/generated/numpy.histogram2d.html

variantstr, default=None

Variant of mutual information to be returned.

get_n_voxels()

Return number of voxels in order [x, y, z].

get_nifti_array_and_affine(standardise=False)

Get image array and affine matrix in canonical nifti configuration.

get_orientation_codes(affine=None, source_type=None)

Get image orientation codes in order [row, column, slice] if image was loaded in dicom-style orientation, or [column, row, slice] if image was loaded in nifti-style orientation.

This returns a list of code strings. Possible codes:

“L” = Left (x axis) “R” = Right (x axis) “P” = Posterior (y axis) “A” = Anterior (y axis) “I” = Inferior (z axis) “S” = Superior (z axis)

Parameters:

affinenp.ndarray, default=None

Custom affine matrix to use when determining orientation codes. If None, self.affine will be used.

source_typestr, default=None

Assumed source type to use when determining orientation codes. If None, self.source_type will be used.

get_orientation_vector(affine=None, source_type=None)

Get image orientation as a row and column vector.

Parameters:

affinenp.ndarray, default=None

Custom affine matrix to use when determining orientation vector. If None, self.affine will be used.

source_typestr, default=None

Assumed source type to use when determining orientation vector. If None, self.source_type will be used.

get_orientation_view()

Determine view corresponding to the image’s orientation.

get_origin(standardise=False, force_standardise=True)

Return origin position in mm in order [x, y, z].

Parameters:

standardisebool, default=False

If False, the origin will be returned for the image as loaded; otherwise, it will be returned for the image in standard dicom-style orientation, such that [column, row, slice] corresponds to the [x, y, z] axes.

force_standardisebool, default=True

If True, the standardised image will be recomputed from self.data even if it has previously been computed.

get_plans()

Return list of Plan objects associated with this Image.

get_plot_aspect_ratio(view, zoom=None, n_colorbars=0, figsize=None)

Estimate the ideal width/height ratio for a plot of this image in a given orientation.

viewstr

Orientation (‘x-y’, ‘x-z’, ‘y-x’, ‘y-z’, ‘z-x’, or ‘z-y’)

zoomfloat/list, default=None

Zoom factors; either a single value for all axes, or three values in order (x, y, z).

n_colorbarsint, default=0

Number of colorbars to make space for.

get_quality(image, metrics=None)

Evaluate quality of this image relative to another.

The metrics considered are:

  • relative structural content;

  • fidelity;

  • correlation quality.

These are defined in:

The three metrics should each have a value between 0 and 1, and are related by:

correlation quality = 0.5 * (relative structural content + fidelity).

Quality scores are returned in a dictionary, with a key corresponding to each metric: “relative_structural_content”, “fidelity”, “correlation_quality”. If a metric isn’t evaluated, the value returned for it is None.

Parameters:

imageskrt.image.Image

Image with respect to which quality metrics are to be calculated.

metrics: list, default=None

List of strings specifying quality metrics to be evaluated. If None, all defined quality metrics are evaluated.

get_range(ax='z')

Get range of the image in mm along a given axis.

get_relative_structural_content(image)

Calculate structural content of this image relative to another.

Uses method get_quality().

Parameter:

imageskrt.image.Image

Image with respect to which relative structural content is to be evaluated

get_rois(name)

Get all instances of ROIs with specified name in image structure sets.

Parameter: name : str

Name for which ROI instances are to be returned.

get_sinogram(force=False, verbose=False, theta=None, ifactor=1, circle=False, rescale=None)

Retrieve Sinogram object corresponding to image.

A sinogram slice is obtained through application of a Radon transform to the original image slice.

Parameters:

forcebool, default=False

The first time that sinogram image is created, it is stored as self.sinogram. It is recreated only if force is set to True.

verbosebool, default=False

If True, print information on progress in sinogram creation.

thetanp.array

Array of projection angles, in degrees. If None, use np.arange(180).

ifactorfloat, default=1

Factor by which to multiply image intensity values before creating sinogram. If image intensity values are in Hounsfield Units, a factor of 0.001 will rescale to intensity values that are close to the linear attenuation coefficient relative to water:

HU = 1000 * (mu - mu_water) / (mu_water) => mu / mu_water = approximately (1 + HU / 1000)

circlebool, default=False

If True, disregard regions of each image slice that are outside the largest circle with centre at the slice centre. In this case, radial values in the sinogram will cover the range from minus circle radius to plus circle radius.

rescaletuple, default=None

Two-element tuple specifying minimum and maximum values for linear rescaling of sinogram greyscale values. If all sinogram values are the same, rescaling sets all values to be the mean of the specified minimum and maximum.

get_size()

Return image sizes in mm in order [x, y, z].

get_slice(view='x-y', sl=None, idx=None, pos=None, flatten=False, force=True, shift=[None, None, None], force_standardise=True, **kwargs)

Get a slice of the data in the correct orientation for plotting. If <sl>, <pos>, and <idx> are all None, the central slice of the image in the orientation specified in <view> will be returned.

Parameters:

viewstr

Orientation; can be “x-y”, “x-z”, “y-x”, “y-z”, “z-x”, or “z-y”.

slint, default=None

Slice number; used if not None.

idxint, default=None

Slice array index; used if not None and <sl> is None.

posfloat, default=None

Slice position in mm; used if not None and <sl> and <idx> are both None.

flattenbool/str, default=False

If True, the image will be flattened across all slices in the orientation specified in <view>; <sl>/<idx>/<pos> will be ignored. If specified as a string, this should be the name of a numpy function with which to combine array values along an axis, for example “sum”, “max”, “min”, “mean”. Otherwise, values are combined by summing.

shiftlist, default=[None, None, None]

Translational shift in order [dx, dy, dz] to apply before returning slice.

get_slice_foreground(idx=0, threshold=None, convex_hull=False, fill_holes=False, dxy=0)

Create foreground mask for image slice.

The foreground is taken to correspond to the largest region of contiguous pixels above a threshold value.

Parameters:

idxint, default=0

Index of slice for which foreground mask is to be obtained.

thresholdint/float, default=None

Intensity value above which pixels are assigned to regions for determination of foreground. If None, use value of Defaults().foreground_threshold. If still None, use Otsu threshold.

convex_hullbool, default=False

If True, return the convex hull of the foreground mask initially obtained.

fill_holesbool, default=False

If False, fill holes in the foreground mask initially obtained.

get_standardised_affine(force=True)

Return affine matrix in standard dicom orientation, where [column, row, slice] corresponds to the [x, y, z] axes.

Parameters:

forcebool, default=True

If True, the standardised array will be recomputed from self.data even if it has previously been computed.

get_standardised_data(force=True)

Return array in standard dicom orientation, where [column, row, slice] corresponds to the [x, y, z] axes. standardised image array.

Parameters:

forcebool, default=True

If True, the standardised array will be recomputed from self.data even if it has previously been computed.

get_standardised_origin(force=True)

Return origin for image in standard dicom orientation, where [column, row, slice] corresponds to the [x, y, z] axes.

Parameters:

forcebool, default=True

If True, the standardised array will be recomputed from self.data even if it has previously been computed.

get_standardised_voxel_size(force=True)

Return voxel size for image in standard dicom orientation, where [column, row, slice] corresponds to the [x, y, z] axes.

Parameters:

forcebool, default=True

If True, the standardised array will be recomputed from self.data even if it has previously been computed.

get_station_name(force=False)

Return name of image-recording station.

The station name will be defined only if the source is DICOM, and the name is included in the metadata. If the name is undefined, return an empty string.

Parameter: force: bool, default=False

If True, try to extract station name from source data, even if already extracted. If False, return any value obtained previously.

get_structure_sets()

Return list of StructureSet objects associated with this Image.

get_translation_to_align(other, alignments=None, default_alignment=2, threshold=None)

Determine translation for aligning <self> to <other>.

This method calls the function of the same name, with <self> and <other> as <im1> and <im2> respectively.

For explanation of parameters, see documentation of skrt.image.get_translation_to_align().

get_translation_to_align_image_rois(other, roi_name1, roi_name2, z_fraction1=None, z_fraction2=None)

Determine translation for aligning ROI of <self> to ROI of <other>.

This method calls the function of the same name, with <self> and <other> as <im1> and <im2> respectively.

For explanation of parameters, see documentation of skrt.image.get_translation_to_align_image_rois().

get_volume(units='mm')

Get image volume in specified units.

Parameter:

unitsstr, default=”mm”
Units of volume. Can be any of:
  • “mm”: return volume in millimetres cubed.

  • “ml”: return volume in millilitres.

  • “voxels”: return volume in number of voxels.

get_voxel_coords()

Get arrays of voxel coordinates in each direction.

get_voxel_size(standardise=False, force_standardise=True)

Return voxel sizes in mm in order [x, y, z].

Parameters:

standardisebool, default=False

If False, the voxel size will be returned for the image as loaded; otherwise, it will be returned for the image in standard dicom-style orientation, such that [column, row, slice] corresponds to the [x, y, z] axes.

force_standardisebool, default=True

If True, the standardised image will be recomputed from self.data even if it has previously been computed.

has_same_data(im, max_diff=0.005)

Check whether this Image has the same data as another Image <im> (i.e. same array shape and same data values), with tolerance <max_diff> on agreement of data values.

has_same_geometry(im, max_diff=0.005, standardise=False, force_standardise=True)

Check whether this Image has the same geometric properties as another Image (i.e. same origins and voxel sizes within tolerance, same shapes).

Parameters: im : skrt.image.Image

Image with which to compare geometry.

max_difffloat, default=0.005

Maximum difference accepted between components of origins and voxel sizes.

standardisebool, default=False

If False, geometry is compared for the images as loaded; otherwise, geometry is compared for the images in standard dicom-style orientation, such that [column, row, slice] corresponds to the [x, y, z] axes.

force_standardisebool, default=True

If True, the standardised image will be recomputed from self.data even if it has previously been computed.

hu_to_mu(mu_water=None)

Assume that image greyscale values are Hounsfield units, and convert to linear attenuation coefficients.

Parameters:

mu_waterfloat, default=None

Value to be used for the linear attenuation coefficient of water. If None, set to the value of skrt.core.Defaults().mu_water.

Note: Image linear attenuation coefficients will be returned in the same units as <mu_water>. For consistency with the units used for image voxel dimensions, it’s recommended that <mu_water> be specified in units of mm^-1.

idx_to_pos(idx, ax, standardise=True)

Convert an array index to a position in mm along a given axis.

idx_to_slice(idx, ax)

Convert an array index to a slice number along a given axis.

label_ax(view, idx, scale_in_mm=True, title=None, xlabel=None, ylabel=None, no_xlabel=False, no_ylabel=False, xticks=None, yticks=None, no_xticks=False, no_yticks=False, no_xtick_labels=False, no_ytick_labels=False, annotate_slice=False, major_xticks=None, major_yticks=None, major_ticks=None, minor_xticks=None, minor_yticks=None, minor_ticks=None, ticks_all_sides=False, no_axis_labels=False, **kwargs)
load(force=False)

Load pixel array from image source. If already loaded and <force> is False, nothing will happen.

Parameters:

forcebool, default=True

If True, the pixel array will be reloaded from source even if it has previously been loaded.

Data loading takes input from self.source and uses this to assign self.data (as well as geometric properties, where relevant). The parameter self.source_type is set to a string indicating the type of source, which can be any of:

“array”:

Data loaded from a numpy array in dicom-style orientation.

“nifti array”:

Data loaded from a numpy array in nifti-style orientation.

“nifti”:

Data loaded from a nifti file.

“dicom”:

Data loaded from one or more dicom file(s).

The loading sequence is as follows:

1. If self.source is a numpy array, self.data will be set to the contents of self.source. If <nifti_array> was set to True when __init__() was called, self.source_type is set to “nifti array”; otherwise, self.source_type is set to “array”.

2. If self.source is a string, then self.source or, if self.source is the path to a directory, self.source/* is passed to glob.glob(). If the resulting list contains a single element, attempt to load a nifti file from this path using the function load_nifti(). If the path points to a valid nifti file, this will return a pixel array and affine matrix, which are assigned to self.data and self.affine, respectively. Set self.source_type to “nifti”.

3. If no data were loaded in step 2 (i.e. self.data is still None), and self.source contains a single path, attempt to load from a numpy binary file at this path using the function load_npy(). If the path points to a valid numpy binary file, this will return a pixel array, which is assigned to self.data. Set source_type to either “nifti array” or “array”, depending on whether <nifti_array> was set to True or False, respectively, when __init__() was called.

4. If no data were loaded in step 4 (i.e. self.data is still None), attempt to load from dicom file(s) or directory at the path(s) in self.source using the function load_dicom(). If successful, this returns a pixel array, affine matrix, default greyscale window centre and width, the last loaded pydicom.dataset.FileDataset object, and a dictionary mapping z positions to paths to the dicom file for that slice. These outputs are used to assign self.data, self.affine, self.dicom_dataset, self._z_paths, and self._z_instance_numbers; self.source_type is set to “dicom”.

5. If no data were loaded in step 5 (i.e. self.data is still None), raise a RuntimeError.

6. If self.data contains a 2D array, convert this to 3D by adding an extra axis.

  1. Apply any downsampling as specificied in __init__().

8. Run self.set_geometry() in order to compute geometric quantities for this Image.

9. If a default window width and window centre were loaded from dicom, use these to set self.default_window to a greyscale window range.

10. If self.title is None and self.source is a filepath, infer a title from the basename of this path.

map_hu(mapping='kv_to_mv')

Map radiodensities in Hounsfield units according to mapping function.

Parameter:

mapping - str, default=’kv_to_mv’

Identifier of mapping function to be used. Currently only the VoxTox mapping from kV CT scan to MV CT scan is implemented.

match_size(image=None, fill_value=None, method='linear')

Match image size to that of a reference image.

After matching, the image voxels are in one-to-one correspondence with those of the reference.

Parameters:

image: skrt.image.Image/None, default=None

Reference image, with which size is to be matched.

fill_value: float/None, default = None

Intensity value to be assigned to any voxels in the resized image that are outside the original image. If set to None, the minimum intensity value of the original image is used.

method: str, default=’linear’

Interpolation method to use. Valid values are ‘linear’ and ‘nearest’

match_voxel_size(image, method='self')

Resample to match z-axis voxel size with that of another Image object.

Note: This method matches voxel size along z-axis only.

To match voxel sizes in all dimensions, use the function skrt.images.match_image_voxel_sizes().

Parameters:

imageImage

Other image to which z-axis voxel size should be matched.

methodstr, default=”self”
String specifying the matching method. Can be any of:
  • “self”:

    Match own z voxel size to that of <image>.

  • “coarse”:

    Resample the image with the smaller z voxels to match that of the image with larger z voxels.

  • “fine”:

    Resample the image with the larger z voxels to match that of the image with smaller z voxels.

mu_to_hu(mu_water=None)

Assume that image greyscale values are linear attenuation coefficients, and convert to Hounsfield units.

Parameter:

mu_waterfloat, default=None

Value to be used for the linear attenuation coefficient of water. If None, set to the value of skrt.core.Defaults().mu_water.

Note: Image linear attenuation coefficients and <mu_water> should have the same units. For consistency with the units used for image voxel dimensions, it’s recommended that linear attenuation coefficients be specified in units of mm^-1.

plot(view='x-y', sl=None, idx=None, pos=None, scale_in_mm=True, ax=None, gs=None, figsize=6, save_as=None, zoom=None, zoom_centre=None, intensity=None, mpl_kwargs=None, show=True, colorbar=False, colorbar_label=None, clb_kwargs=None, clb_label_kwargs=None, title=None, xlabel=None, ylabel=None, no_xlabel=False, no_ylabel=False, xticks=None, yticks=None, no_xticks=False, no_yticks=False, no_xtick_labels=False, no_ytick_labels=False, annotate_slice=False, major_xticks=None, major_yticks=None, major_ticks=None, minor_xticks=None, minor_yticks=None, minor_ticks=None, ticks_all_sides=False, no_axis_labels=False, rois=None, roi_plot_type='contour', roi_opacity=None, roi_linewidth=None, consensus_type=None, exclude_from_consensus=None, consensus_color='blue', consensus_linewidth=None, legend=False, roi_kwargs=None, centre_on_roi=None, legend_bbox_to_anchor=None, legend_loc='lower left', dose=None, dose_opacity=0.5, dose_kwargs=None, grid=None, grid_opacity=1.0, grid_kwargs=None, flatten=False, xlim=None, ylim=None, zlim=None, shift=[None, None, None], mask=None, mask_threshold=0.5, masked=True, invert_mask=False, mask_color='black', jacobian=None, jacobian_opacity=0.8, jacobian_range=None, jacobian_kwargs=None, df=None, df_plot_type='quiver', df_spacing=30, df_opacity=None, df_kwargs=None)

Plot a 2D slice of the image.

Parameters:

viewstr/None, default=’x-y’

Orientation in which to plot the image. Can be any of ‘x-y’, ‘x-z’, ‘y-x’, ‘y-z’, ‘z-x’, and ‘z-y’. If None, the initial view is chosen to match the image orienation.

slint, default=None

Slice number to plot. Takes precedence over <idx> and <pos> if not None. If all of <sl>, <idx>, and <pos> are None, the central slice will be plotted.

idxint, default=None

Index of the slice in the array to plot. Takes precendence over <pos>.

posfloat, default=None

Position in mm of the slice to plot. Will be rounded to the nearest slice. Only used if <sl> and <idx> are both None.

standardisedbool, default=True

If True, a standardised version of the image array will be plotted such that the axis labels are correct.

scale_in_mmbool, default=True

If True, axis labels will be in mm; otherwise, they will be slice numbers.

axmatplotlib.pyplot.Axes, default=None

Axes on which to plot. If None, new axes will be created.

gsmatplotlib.gridspec.GridSpec, default=None

If not None and <ax> is None, new axes will be created on the current matplotlib figure with this gridspec.

figsizefloat, default=None

Figure height in inches; only used if <ax> and <gs> are None.

zoomint/float/tuple, default=None

Factor by which to zoom in. If a single int or float is given, the same zoom factor will be applied in all directions. If a tuple of three values is given, these will be used as the zoom factors in each direction in the order (x, y, z). If None, the image will not be zoomed in.

zoom_centretuple, default=None

Position around which zooming is applied. If None, the centre of the image will be used.

colorbarint/bool, default=False

Indicate whether to display colour bar(s): - 1 or True: colour bar for main image; - 2: colour bars for main image and for any associated image or overlay; - 0 or False: no colour bar.

colorbar_labelstr, default=’HU’

Label for the colorbar, if drawn.

clb_kwargsdict, default=None

Dictionary of keyword arguments to pass to pyplot.colorbar().

clb_label_kwargsdict, default=None

Dictionary of keyword arguments to pass to colorbar.set_label().

intensitylist, default=None

Two-item list containing min and max intensity for plotting. Supercedes ‘vmin’ and ‘vmax’ in <mpl_kwargs>.

mpl_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib.imshow().

showbool, default=True

If True, the plotted figure will be shown via matplotlib.pyplot.show().

titlestr, default=None

Custom title for the plot. If None, a title inferred from the image filename will be used. If False or ‘’, no title will be added.

xlabelstr, default=None

Custom label for the x axis. If None, the label is set to be the coordinate axis and units, for example “x (mm)”. If False or ‘’, the x axis will not be labelled.

ylabelstr, default=None

Custom label for the y axis. If None, the label is set to be the coordinate axis and units, for example “y (mm)”. If False or ‘’, the x axis will not be labelled.

no_xlabelbool, default=False

If True, the x axis will not be labelled.

no_ylabelbool, default=False

If True, the y axis will not be labelled.

xtickstuple/dict, default=None

Tick locations and custom tick labels for the x axis.

ytickstuple/dict, default=None

Tick locations and custom tick labels for the y axis.

no_xticksbool, default=False

If True, ticks (and their labels) on the x axis will not be shown.

no_yticksbool, default=False

If True, ticks (and their labels) on the y axis will not be shown.

no_xtick_labelsbool, default=False

If True, ticks on the x axis will not be labelled.

no_ytick_labelsbool, default=False

If True, ticks on the y axis will not be labelled.

no_axis_labelbool, default=False

If True, axis labels and axis values aren’t shown.

annotate_slicebool/str/dict/list, default=False

Specification of slice annotations:

  • bool: annotate with slice position (scale_in_mm True)

or number (scale_in_mm False), in default colour (white).

  • str: annotate with slice position or number in colour

specified by string.

  • dict: annotation dictionary, containing keyword-value pairs

to be passed to annotate() method of figure axes. The following defaults are defined:

‘text’: slice position or number; ‘xy’: (0.05, 0.93) ‘xycoords’: ‘axes fraction’ ‘color’: ‘white’ ‘fontsize’: ‘large’

  • list: list of annotation dictionaries

For information on all parameters that can be passed to annotate() method, see: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.annotate.html

major_xticksfloat, default=None

If not None, this value will be used as the interval between major tick marks on the x-axis. Otherwise, automatic matplotlib axis tick spacing will be used.

major_yticksfloat, default=None

If not None, this value will be used as the interval between major tick marks on the y-axis. Otherwise, automatic matplotlib axis tick spacing will be used.

major_ticksfloat, default=None

If not None, this value will be used as the interval between major tick marks. Otherwise, automatic matplotlib axis tick spacing will be used. This parameter applies to both x-axis and y-axis, but is overridden by a non-None value for major_xticks or major_yticks.

minor_xticksint, default=None

If None, no minor ticks will be plotted for the x-axis. Otherwise, this value will be the number of minor tick divisions per major tick interval.

minor_yticksint, default=None

If None, no minor ticks will be plotted for the y-axis. Otherwise, this value will be the number of minor tick divisions per major tick interval.

minor_ticksint, default=None

If None, no minor ticks will be plotted. Otherwise, this value will be the number of minor tick divisions per major tick interval. This parameter applies to both x-axis and y-axis, but is overridden by a non-None value for minor_xticks or minor_yticks.

ticks_all_sidesbool, default=False

If True, major (and minor if using) tick marks will be shown above and to the right hand side of the plot as well as below and to the left. The top/right ticks will not be labelled.

roisint/str, default=None

Option for which structure set should be plotted (if the Image owns any structure sets). Can be:

  • None: no structure sets will be plotted.

  • The index in self.structure_sets of the structure set (e.g. to plot the newest structure set, use rois=-1)

  • ‘all’: all structure sets will be plotted.

roi_plot_typestr, default=’contour’

ROI plotting type (see ROI.plot() for options).

roi_opacityfloat, default=None

Opacity to use if plotting ROI as mask (i.e. roi_plot_type “mask”, “filled”, or “filled centroid”). If None, opacity will be 1 by default for solid mask plots and 0.3 by default for filled plots.

roi_linewidthfloat, default=None

Width of ROI contour lines. If None, the matplotlib default setting will be used.

consensus_typestr, default=None

If not None, the consensus of all ROIs will be plotting rather than plotting ROIs individually. Requires <rois> to be a single StructureSet. Options are “majority”, “sum”, “overlap”, “staple”.

exclude_from_consensusstr, default=None

If set to the name of an ROI and consensus_type is a valid consensus type, this ROI will be excluded from the consensus calculation and plotted separately on top of the consensus ROI.

consensus_colormatplotlib color, default=”white”

Color in which to plot consensus contour.

consensus_linewidthfloat, default=None

Linewidth of consensus contour. If None, the default matplotlib linewidth + 1 will be used (such that consensus contours are thicker than standard contours).

legendbool, default=False

If True, a legend will be drawn containing ROI names.

roi_kwargsdict, default=None

Extra arguments to provide to ROI plotting via the ROI.plot() method.

centre_on_roistr, default=None

Name of ROI on which to centre, if no idx/sl/pos is given. If <zoom> is given but no <zoom_centre>, the zoom will also centre on this ROI.

legend_bbox_to_anchortuple, default=None

Specify placement of ROI legend. - If a four-element tuple, the elements specify

(x, y, width, height) of the legend bounding box.

  • If a two-element tuple, the elements specify (x, y) of the part of the legend bounding box specified by legend_loc.

legend_locstr, default=’lower left’

Legend location for ROI legend.

doseskrt.dose.Dose / int, default=None

Dose field to overlay on the image. Can be either a skrt.dose.Dose object or an integer referring to the dose at a given index in self.doses (e.g. to plot the last dose assigned to this Image, set dose=-1).

dose_opacityfloat, default=0.5

Opacity of overlaid dose field, if <dose> is not None.

dose_kwargsdict, default=None

Extra arguments to provide to the mpl_kwargs argument in the dose plotting method.

xlim, ylimtuples, default=None

Custom limits on the x and y axes of the plot.

maskImage/list/ROI/str/StructureSet, default=None

Image object representing a mask or a source from which an Image object can be initialised. In addition to the sources accepted by the Image constructor, the source may be an ROI, a list of ROIs or a StructureSet. In the latter cases, the mask image is derived from the ROI mask(s).

mask_thresholdfloat, default=0.5

Threshold for mask data. Values above and below this value are set to True and False respectively. Taken into account only if the mask image has non-boolean data.

maskedbool, default=True

If True and a mask is specified, the image is masked.

invert_maskbool, default=False

If True and a mask is applied, the mask will be inverted.

mask_colormatplotlib color, default=”black”

color in which to plot masked areas.

jacobianskrt.registration.Jacobian, default=None

Jacobian determinannt to be overlaid on plot. This parameter is ignored if a non-null value is specified for dose.

jacobian_opacityfloat, default=0.8

Initial opacity of the overlaid jacobian determinant. Can later be changed interactively.

jacobian_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib.pyplot.imshow for the jacobian determinant. For options, see: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html

Some useful keywords are:

  • ‘cmap’: colormap (default=’jacobian’ - custom colour map).

  • ‘interpolation’: interpolation method (default=’antialiased’)

df_plot_typestr, default=’quiver’

Option for initial plotting of deformation field. Can be ‘quiver’, ‘grid’, ‘x-displacement’, ‘y-displacement’, ‘z-displacement’, ‘3d-displacement’, or ‘none’. All quantities relate to the mapping of points from fixed image to moving image in image registration.

df_spacingint/tuple, default=30

Spacing between arrows on the quiver plot/gridlines on the grid plot of a deformation field. Can be a single value for spacing in all directions, or a tuple with values for (x, y, z). Dimensions are mm if <scale_in_mm> is True, or voxels if <scale_in_mm> is False.

df_opacityfloat, default=0.5

Initial opacity of the overlaid deformation field.

dfstr/skrt.registration.DeformationField/list, default=None

Source(s) of deformation field(s) to overlay on each plot.

df_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib when plotting the deformation field.

For grid plotting options, see https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html. Some useful keywords are:

  • ‘linewidth’: default=2

  • ‘color’: default=’green’

For quiver plotting options, see https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.quiver.html.

roi_plot_typestr, default=’contour’

Option for initial plot of ROIs. Can be ‘contour’, ‘mask’, ‘filled’, or ‘none’.

gridstring/nifti/array/list, default=None

Source(s) of grid array(s) to overlay on image (see valid image sources for <images>).

grid_opacityfloat, default=1.0

Opacity of the overlaid grid.

grid_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib.pyplot.imshow for the grid. See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html for options.

pos_to_idx(pos, ax, return_int=True, standardise=True)

Convert a position in mm to an array index along a given axis.

pos_to_slice(pos, ax, return_int=True, standardise=True)

Convert a position in mm to a slice number along a given axis.

print_geometry(float_format='.4f')
remove_bolus(structure_set=None, bolus_names=None, intensity=None)

Attempt to remove bolus from image.

In treatment planning, ROIs labelled as bolus may be defined on the skin, and are assigned a radiodensity of water (zero) to help guide the treatment optimiser. The original image is approximately recovered by overwriting with the radiodensity of air.

Parameters: structure_set : skrt.structures.StructureSet

Structure set to search for ROIs labelled as bolus. If None, the image’s earliest associated structure set is used.

bolus_nameslist, default=None

List of names, optionally including wildcards, with which bolus may be labelled. If None, use skrt.image._default_bolus_names.

intensityint/float, default=None

Intensity value to be assigned to voxels of ROI labelled as bolus. If None, use image’s minimum value.

resample(voxel_size=(1, 1, 1), order=1)

Resample image to have particular voxel sizes.

Parameters:

voxel_size: int/float/tuple/list, default =(1, 1, 1)

Voxel size to which image is to be resampled. If voxel_size is a tuple or list, then it’s taken to specify voxel sizes in mm in the order x, y, z. If voxel_size is an int or float, then it’s taken to specify the voxel size in mm along all axes.

order: int, default = 1

Order of the b-spline used in interpolating voxel intensity values.

rescale(v_min=0.0, v_max=1.0, constant=0.5)

Linearly rescale image greyscale values, so that they span a specified range.

Parameters:

v_min: float, default=0.0

Minimum greyscale value after rescaling.

v_max: float, default=1.0

Maximum greyscale value after rescaling.

constant: float, default=0.5

Greyscale value to assign after rescaling if all values in the original image are the same. If None, original value is kept.

resize(image_size=None, origin=None, voxel_size=None, fill_value=None, image_size_unit=None, centre=None, keep_centre=False, method='linear')

Resize image to specified image size, voxel size and origin.

Parameters:

image_sizetuple/list/None, default=None

Image sizes in order (x,y,z) to which image is to be resized. If None, the image’s existing size in mm is kept. If a value in the tuple/list is None, the relevant existing value is kept. The unit of measurement (‘voxel’ or ‘mm’) is specified via image_size_unit. If the size is in mm, and isn’t an integer multiple of voxel_size, resizing won’t be exact.

origintuple/list/None, default=None

Origin position in mm in order (x, y, z). If None, the image’s existing origin is kept. If a value in the tuple/list is None, the relevant existing value is kept. Disregarded if centre isn’t None, or if keep_centre is True.

voxel_sizetuple/list/None, default=None

Voxel sizes in mm in order (x, y, z). If None, the image’s existing voxel size is kept. If a value in the tuple/list is None, the relevant existing value is kept.

fill_value: float/None, default = None

Intensity value to be assigned to any voxels in the resized image that are outside the original image. If set to None, the minimum intensity value of the original image is used.

image_size_unit: str, default=None

Unit of measurement (‘voxel’ or ‘mm’) for image_size. If None, use ‘voxel’.

centretuple/list/None, default=None

Position (x, y, z) in mm in the original image to be set as centre for the resized image. Disregarded if None. Otherwise takes priority over origin and keep_centre. If a value in the tuple/list is None, the relevant value from the original image centre is kept.

keep_centre: bool, default=False

If True, make the centre of the initial image the centre of the resized image, disregarding the value passed to origin. Disregarded if the value of the centre parameter isn’t None.

method: str, default=’linear’

Interpolation method to use. Valid values are ‘linear’ and ‘nearest’

select_foreground(threshold=None, convex_hull=False, fill_holes=True, dxy=0, background=None)

Modify image to show intensity information only for foreground.

Slice by slice, the foreground is taken to correspond to the largest region of contiguous pixels above a threshold value. Voxels outside the foreground region are all assigned the same same (background) intensity value.

Parameters:

thresholdint/float, default=None

Intensity value above which pixels in a slice are assigned to regions for determination of foreground. If None, use value of Defaults().foreground_threshold. If still None, use Otsu threshold.

convex_hullbool, default=False

If True, create mask from the convex hulls of the slice foreground masks initially obtained.

fill_holesbool, default=False

If False, fill holes in the slice foreground masks initially obtained.

backgroundint/float, default=None

Intensity value to be assigned to background voxels. If None, the image’s minimum value is used.

set_ax(view=None, ax=None, gs=None, figsize=None, zoom=None, colorbar=False)

Set up axes for this Image.

set_geometry()

Set geometric properties for this image. Should be called once image data has been loaded. Sets the following properties:

Affine matrix (self.affine):

4x4 affine matrix. If initially None, this is computed from self.voxel_size and self.origin.

Voxel sizes (self.voxel_size):

List of [x, y, z] voxel sizes in mm. If initially None, this is computed from self.affine.

Origin position (self.origin):

List of [x, y, z] origin coordinates in mm. If initially None, this is computed from self.affine.

Number of voxels (self.n_voxels):

List of number of voxels in the [x, y, z] directions. Computed from self.data.shape.

Limits (self.lims):

List of minimum and maximum array positions in the [x, y, z] directions (corresponding the centres of the first and last voxels). Calculated from standardised origin, voxel sizes, and image shape.

Image extent (self.image_extent):

List of minimum and maximum positions of the edges of the array in the [x, y, z] directions. Calculated from self.lims +/- half a voxel size.

Plot extent (self.plot_extent):

Dict of plot extents for each orientation. Given in the form of a list [x1, x2, y1, y2], which is the format needed for the <extent> argument for matplotlib plotting.

Image sizes (self.image_size):

List of [x, y, z] image sizes in mm.

slice_to_idx(sl, ax)

Convert a slice number to an array index along a given axis.

slice_to_pos(sl, ax, standardise=True)

Convert a slice number to a position in mm along a given axis.

standardise_data()

Manipulate data array and affine matrix into standard dicom orientation, where [column, row, slice] corresponds to the [x, y, z] axes; assign results to self._sdata and self._saffine, respectively. Standardised voxel sizes (self._svoxel_size) and origin position (self._sorigin) will also be inferred from self._affine.

transform(scale=1, translation=[0, 0, 0], rotation=[0, 0, 0], centre=[0, 0, 0], resample='fine', restore=True, order=1, fill_value=None)

Apply three-dimensional similarity transform using scikit-image.

The image is first translated, then is scaled and rotated about the centre coordinates

Parameters:

scalefloat, default=1

Scaling factor.

translationlist, default=[0, 0, 0]

Translation in mm in the [x, y, z] directions.

rotationfloat, default=0

Euler angles in degrees by which to rotate the image. Angles are in the order pitch (rotation about x-axis), yaw (rotation about y-axis), roll (rotation about z-axis).

centrelist, default=[0, 0, 0]

Coordinates in mm in [x, y, z] about which to perform rotation and scaling of translated image.

resample: float/string, default=’fine’

Resampling to be performed before image transformation. If resample is a float, then the image is resampled so that this is the voxel size in mm along all axes. If the transformation involves scaling or rotation in an image projection where voxels are non-square: if resample is ‘fine’ then voxels are resampled to have their smallest size along all axes; if resample is ‘coarse’ then voxels are resampled to have their largest size along all axes.

restore: bool, default=True

In case that image has been resampled: if True, restore original voxel size for transformed iamge; if False, keep resampled voxel size for transformed image.

order: int, default = 1

Order of the b-spline used in interpolating voxel intensity values.

fill_value: float/None, default = None

Intensity value to be assigned to any voxels in the resized image that are outside the original image. If set to None, the minimum intensity value of the original image is used.

translate_origin(translation=[0, 0, 0])

Translate origin, effectively changing image position.

Parameter:

translationlist, default=[0, 0, 0]

Translation in mm in the [x, y, z] directions.

view(images=None, **kwargs)

View self with BetterViewer along with any additional images in <images>. Any **kwargs will be passed to BetterViewer initialisation.

write(outname, standardise=False, write_geometry=True, nifti_array=False, overwrite=True, header_source=None, patient_id=None, patient_position=None, modality=None, root_uid=None, verbose=True, header_extras={})

Write image data to a file. The filetype will automatically be set based on the extension of <outname>:

(a) *.nii or *.nii.gz: Will write to a nifti file with canonical nifti array and affine matrix.

(b) *.npy: Will write the dicom-style numpy array to a binary filem unless <nifti_array> is True, in which case the canonical nifti-style array will be written. If <write_geometry> is True, a text file containing the voxel sizes and origin position will also be written in the same directory.

(c) *.dcm: Will write to dicom file(s) (1 file per x-y slice) in the directory of the filename given, named by slice number.

(d) No extension: Will create a directory at <outname> and write to dicom file(s) in that directory (1 file per x-y slice), named by slice number.

If (c) or (d) (i.e. writing to dicom), the header data will be set in one of three ways:

  • If the input source was not a dicom, <dicom_for_header> is None, a brand new dicom with freshly generated UIDs will be created.

  • If <dicom_for_header> is set to the path to a dicom file, that dicom file will be used as the header.

  • Otherwise, if the input source was a dicom or directory containing dicoms, the header information will be taken from the input dicom file.

In addition, when writing to dicom, the header obtained as outlined above will be updated via attribute-value pairs passed via the dictionary header_extras.

zoom_ax(view, zoom=None, zoom_centre=None)

Zoom in on axes if needed.

class skrt.image.ImageComparison(im1, im2, plot_type='overlay', title=None, **kwargs)

Bases: Image

Plot comparisons of two images and calculate comparison metrics.

__init__(im1, im2, plot_type='overlay', title=None, **kwargs)

Initialise from a medical image source.

Parameters:

pathstr/array/Nifti1Image, default = “”

Source of image data. Can be either:

  1. A string, optionally with wildcards, containing the path to one or multiple dicom files, the path to a directory containg dicom files, or the path to a single nifti file;

  2. A list of paths, optionally with wildcards, to dicom files;

  3. A string, optionally containing wildcards, containing the path to a single numpy file containing a 2D or 3D array;

  4. A 2D or 3D numpy array;

  5. A nibabel.nifti1.Nifti1Image object;

  6. An existing Image object to be cloned; in this case, all other input args except <title> will be ignored, as these will be taken from the existing Image.

Notes:

  1. If path points to a single file, all files in the same directory as this file are considered also.

2. When path resolves to multiple dicom files, only files that match the values of the first file for the dicom attributes: “StudyInstanceUID”, “SeriesNumber”, “Modality”, “ImageOrientationPatient”. When path points to a single file in a directory with others, this file is taken as the first file. Otherwise, files are sorted according to natural sort order (so “2.dcm” before “11.dcm”). To load images from files in a single directory (or in a directory tree) that may have different values for these, it could be better to use the skrt.patient.Patient class:

from skrt import Patient p = Patient(“path/to/directory”, unsorted_dicom=True)

For more details, see documentation of Patient class.

loadbool, default=True

If True, the image data will be immediately loaded. Otherwise, it can be loaded later with the load() method.

titlestr, default=None

Title to use when plotting the image. If None and <source> is a path, a title will be automatically generated from the filename.

affine4x4 array, default=None

Array containing the affine matrix to use if <source> is a numpy array or path to a numpy file. If not None, this takes precendence over <voxel_size> and <origin>.

voxel_sizetuple, default=(1, 1, 1)

Voxel sizes in mm in order (x, y, z) to use if <source> is a numpy array or path to a numpy file and <affine> is not provided.

origintuple, default=(0, 0, 0)

Origin position in mm in order (x, y, z) to use if <source> is a numpy array or path to a numpy file and <affine> is not provided.

nifti_arraybool, default=False

If True and <source> is a numpy array or numpy file, the array will be treated as a nifti-style array, i.e. (x, y, z) in (row, column, slice), as opposed to dicom style.

downsampleint/list, default=None

Amount by which to downsample the image. Can be a single value for all axes, or a list containing downsampling amounts in order (x, y, z).

dtypetype, default=None

Type to which loaded data should be cast.

auto_timestampbool default=False

If true and no valid timestamp is found within the path string, timestamp generated from current date and time.

default_intensitytuple,None default=(-200, 300)

Default intensity range for image display. This can be specified as a two-element tuple, giving minimum and maximum, or if set to None then intensity range used is from the minimum of zero and the image minimum, to the image maximum. If WindowCenter and WindowWidth are defined in a DICOM source file, these values will be used instead to define the default intensity range.

log_level: str/int/None, default=None

Severity level for event logging. If the value is None, log_level is set to the value of skrt.core.Defaults().log_level.

get_difference(view='x-y', sl=None, idx=None, pos=None, invert=False, ab=False, reset_slices=True)

Get array containing difference between two Images.

get_dta(view='x-y', sl=None, idx=None, pos=None, tolerance=None, reset_slices=True)

Compute distance to agreement array on current slice.

get_gamma(view='x-y', sl=None, pos=None, idx=None, invert=False, dta_crit=None, diff_crit=None, reset_slices=True)

Get gamma index on current slice.

get_plot_aspect_ratio(*args, **kwargs)

Get relative width of first image.

load(force=False)

Load associated images, and set array limits in [x, y, z] directions.

Parameter:

forcebool, default=True

If True, associated images will be reloaded from source, even if previously loaded.

plot(view='x-y', sl=None, idx=None, pos=None, scale_in_mm=True, invert=False, ax=None, mpl_kwargs=None, show=True, figsize=None, zoom=None, zoom_centre=None, plot_type=None, cb_splits=8, overlay_opacity=0.5, overlay_legend=False, overlay_legend_bbox_to_anchor=None, overlay_legend_loc=None, colorbar=False, colorbar_label=None, show_mse=False, dta_tolerance=None, dta_crit=None, diff_crit=None, use_cached_slices=False, **kwargs)

Plot a 2D slice of the image.

Parameters:

viewstr/None, default=’x-y’

Orientation in which to plot the image. Can be any of ‘x-y’, ‘x-z’, ‘y-x’, ‘y-z’, ‘z-x’, and ‘z-y’. If None, the initial view is chosen to match the image orienation.

slint, default=None

Slice number to plot. Takes precedence over <idx> and <pos> if not None. If all of <sl>, <idx>, and <pos> are None, the central slice will be plotted.

idxint, default=None

Index of the slice in the array to plot. Takes precendence over <pos>.

posfloat, default=None

Position in mm of the slice to plot. Will be rounded to the nearest slice. Only used if <sl> and <idx> are both None.

standardisedbool, default=True

If True, a standardised version of the image array will be plotted such that the axis labels are correct.

scale_in_mmbool, default=True

If True, axis labels will be in mm; otherwise, they will be slice numbers.

axmatplotlib.pyplot.Axes, default=None

Axes on which to plot. If None, new axes will be created.

gsmatplotlib.gridspec.GridSpec, default=None

If not None and <ax> is None, new axes will be created on the current matplotlib figure with this gridspec.

figsizefloat, default=None

Figure height in inches; only used if <ax> and <gs> are None.

zoomint/float/tuple, default=None

Factor by which to zoom in. If a single int or float is given, the same zoom factor will be applied in all directions. If a tuple of three values is given, these will be used as the zoom factors in each direction in the order (x, y, z). If None, the image will not be zoomed in.

zoom_centretuple, default=None

Position around which zooming is applied. If None, the centre of the image will be used.

colorbarint/bool, default=False

Indicate whether to display colour bar(s): - 1 or True: colour bar for main image; - 2: colour bars for main image and for any associated image or overlay; - 0 or False: no colour bar.

colorbar_labelstr, default=’HU’

Label for the colorbar, if drawn.

clb_kwargsdict, default=None

Dictionary of keyword arguments to pass to pyplot.colorbar().

clb_label_kwargsdict, default=None

Dictionary of keyword arguments to pass to colorbar.set_label().

intensitylist, default=None

Two-item list containing min and max intensity for plotting. Supercedes ‘vmin’ and ‘vmax’ in <mpl_kwargs>.

mpl_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib.imshow().

showbool, default=True

If True, the plotted figure will be shown via matplotlib.pyplot.show().

titlestr, default=None

Custom title for the plot. If None, a title inferred from the image filename will be used. If False or ‘’, no title will be added.

xlabelstr, default=None

Custom label for the x axis. If None, the label is set to be the coordinate axis and units, for example “x (mm)”. If False or ‘’, the x axis will not be labelled.

ylabelstr, default=None

Custom label for the y axis. If None, the label is set to be the coordinate axis and units, for example “y (mm)”. If False or ‘’, the x axis will not be labelled.

no_xlabelbool, default=False

If True, the x axis will not be labelled.

no_ylabelbool, default=False

If True, the y axis will not be labelled.

xtickstuple/dict, default=None

Tick locations and custom tick labels for the x axis.

ytickstuple/dict, default=None

Tick locations and custom tick labels for the y axis.

no_xticksbool, default=False

If True, ticks (and their labels) on the x axis will not be shown.

no_yticksbool, default=False

If True, ticks (and their labels) on the y axis will not be shown.

no_xtick_labelsbool, default=False

If True, ticks on the x axis will not be labelled.

no_ytick_labelsbool, default=False

If True, ticks on the y axis will not be labelled.

no_axis_labelbool, default=False

If True, axis labels and axis values aren’t shown.

annotate_slicebool/str/dict/list, default=False

Specification of slice annotations:

  • bool: annotate with slice position (scale_in_mm True)

or number (scale_in_mm False), in default colour (white).

  • str: annotate with slice position or number in colour

specified by string.

  • dict: annotation dictionary, containing keyword-value pairs

to be passed to annotate() method of figure axes. The following defaults are defined:

‘text’: slice position or number; ‘xy’: (0.05, 0.93) ‘xycoords’: ‘axes fraction’ ‘color’: ‘white’ ‘fontsize’: ‘large’

  • list: list of annotation dictionaries

For information on all parameters that can be passed to annotate() method, see: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.annotate.html

major_xticksfloat, default=None

If not None, this value will be used as the interval between major tick marks on the x-axis. Otherwise, automatic matplotlib axis tick spacing will be used.

major_yticksfloat, default=None

If not None, this value will be used as the interval between major tick marks on the y-axis. Otherwise, automatic matplotlib axis tick spacing will be used.

major_ticksfloat, default=None

If not None, this value will be used as the interval between major tick marks. Otherwise, automatic matplotlib axis tick spacing will be used. This parameter applies to both x-axis and y-axis, but is overridden by a non-None value for major_xticks or major_yticks.

minor_xticksint, default=None

If None, no minor ticks will be plotted for the x-axis. Otherwise, this value will be the number of minor tick divisions per major tick interval.

minor_yticksint, default=None

If None, no minor ticks will be plotted for the y-axis. Otherwise, this value will be the number of minor tick divisions per major tick interval.

minor_ticksint, default=None

If None, no minor ticks will be plotted. Otherwise, this value will be the number of minor tick divisions per major tick interval. This parameter applies to both x-axis and y-axis, but is overridden by a non-None value for minor_xticks or minor_yticks.

ticks_all_sidesbool, default=False

If True, major (and minor if using) tick marks will be shown above and to the right hand side of the plot as well as below and to the left. The top/right ticks will not be labelled.

roisint/str, default=None

Option for which structure set should be plotted (if the Image owns any structure sets). Can be:

  • None: no structure sets will be plotted.

  • The index in self.structure_sets of the structure set (e.g. to plot the newest structure set, use rois=-1)

  • ‘all’: all structure sets will be plotted.

roi_plot_typestr, default=’contour’

ROI plotting type (see ROI.plot() for options).

roi_opacityfloat, default=None

Opacity to use if plotting ROI as mask (i.e. roi_plot_type “mask”, “filled”, or “filled centroid”). If None, opacity will be 1 by default for solid mask plots and 0.3 by default for filled plots.

roi_linewidthfloat, default=None

Width of ROI contour lines. If None, the matplotlib default setting will be used.

consensus_typestr, default=None

If not None, the consensus of all ROIs will be plotting rather than plotting ROIs individually. Requires <rois> to be a single StructureSet. Options are “majority”, “sum”, “overlap”, “staple”.

exclude_from_consensusstr, default=None

If set to the name of an ROI and consensus_type is a valid consensus type, this ROI will be excluded from the consensus calculation and plotted separately on top of the consensus ROI.

consensus_colormatplotlib color, default=”white”

Color in which to plot consensus contour.

consensus_linewidthfloat, default=None

Linewidth of consensus contour. If None, the default matplotlib linewidth + 1 will be used (such that consensus contours are thicker than standard contours).

legendbool, default=False

If True, a legend will be drawn containing ROI names.

roi_kwargsdict, default=None

Extra arguments to provide to ROI plotting via the ROI.plot() method.

centre_on_roistr, default=None

Name of ROI on which to centre, if no idx/sl/pos is given. If <zoom> is given but no <zoom_centre>, the zoom will also centre on this ROI.

legend_bbox_to_anchortuple, default=None

Specify placement of ROI legend. - If a four-element tuple, the elements specify

(x, y, width, height) of the legend bounding box.

  • If a two-element tuple, the elements specify (x, y) of the part of the legend bounding box specified by legend_loc.

legend_locstr, default=’lower left’

Legend location for ROI legend.

doseskrt.dose.Dose / int, default=None

Dose field to overlay on the image. Can be either a skrt.dose.Dose object or an integer referring to the dose at a given index in self.doses (e.g. to plot the last dose assigned to this Image, set dose=-1).

dose_opacityfloat, default=0.5

Opacity of overlaid dose field, if <dose> is not None.

dose_kwargsdict, default=None

Extra arguments to provide to the mpl_kwargs argument in the dose plotting method.

xlim, ylimtuples, default=None

Custom limits on the x and y axes of the plot.

maskImage/list/ROI/str/StructureSet, default=None

Image object representing a mask or a source from which an Image object can be initialised. In addition to the sources accepted by the Image constructor, the source may be an ROI, a list of ROIs or a StructureSet. In the latter cases, the mask image is derived from the ROI mask(s).

mask_thresholdfloat, default=0.5

Threshold for mask data. Values above and below this value are set to True and False respectively. Taken into account only if the mask image has non-boolean data.

maskedbool, default=True

If True and a mask is specified, the image is masked.

invert_maskbool, default=False

If True and a mask is applied, the mask will be inverted.

mask_colormatplotlib color, default=”black”

color in which to plot masked areas.

jacobianskrt.registration.Jacobian, default=None

Jacobian determinannt to be overlaid on plot. This parameter is ignored if a non-null value is specified for dose.

jacobian_opacityfloat, default=0.8

Initial opacity of the overlaid jacobian determinant. Can later be changed interactively.

jacobian_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib.pyplot.imshow for the jacobian determinant. For options, see: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html

Some useful keywords are:

  • ‘cmap’: colormap (default=’jacobian’ - custom colour map).

  • ‘interpolation’: interpolation method (default=’antialiased’)

df_plot_typestr, default=’quiver’

Option for initial plotting of deformation field. Can be ‘quiver’, ‘grid’, ‘x-displacement’, ‘y-displacement’, ‘z-displacement’, ‘3d-displacement’, or ‘none’. All quantities relate to the mapping of points from fixed image to moving image in image registration.

df_spacingint/tuple, default=30

Spacing between arrows on the quiver plot/gridlines on the grid plot of a deformation field. Can be a single value for spacing in all directions, or a tuple with values for (x, y, z). Dimensions are mm if <scale_in_mm> is True, or voxels if <scale_in_mm> is False.

df_opacityfloat, default=0.5

Initial opacity of the overlaid deformation field.

dfstr/skrt.registration.DeformationField/list, default=None

Source(s) of deformation field(s) to overlay on each plot.

df_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib when plotting the deformation field.

For grid plotting options, see https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html. Some useful keywords are:

  • ‘linewidth’: default=2

  • ‘color’: default=’green’

For quiver plotting options, see https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.quiver.html.

roi_plot_typestr, default=’contour’

Option for initial plot of ROIs. Can be ‘contour’, ‘mask’, ‘filled’, or ‘none’.

gridstring/nifti/array/list, default=None

Source(s) of grid array(s) to overlay on image (see valid image sources for <images>).

grid_opacityfloat, default=1.0

Opacity of the overlaid grid.

grid_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib.pyplot.imshow for the grid. See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html for options.

set_slices(view, sl=None, idx=None, pos=None, use_cached_slices=False)

Get slice of each image and set to self.slices.

view(**kwargs)

View self with BetterViewer.

class skrt.image.Sinogram(path='', load=True, title=None, affine=None, voxel_size=(1, 1, 1), origin=(0, 0, 0), nifti_array=False, downsample=None, dtype=None, auto_timestamp=False, default_intensity=(-200, 300), log_level=None, rgb_weights=(0.299, 0.587, 0.114), rgb_rescale_slope=100, rgb_rescale_intercept=0)

Bases: Image

Class representing a sinogram.

This class inherits the constructor and all functionality of the Image class, and implements additional methods specific to working with sinograms.

Methods:

  • apply_filter() : Apply a named filter to sinogram.

  • filtered() : Return the result of applying a named filter to sinogram.

  • backprojected() : Return image reconstructed from sinogram through backprojection.

apply_filter(filter_name=None)

Apply a named filter to sinogram.

A Fourier transform maps the initial sinogram to the frequency domain, the named filter is applied, and an inverse Fourier transform maps the result back to the spatial domain. The initial and final sinogram have the same geometry.

Filtering is performed in-place. To obtain a copy of the original with filter applied, use: Sinogram.filtered().

This method is based on the scikit-image function skimage.transform.iradon(): https://scikit-image.org/docs/stable/api/skimage.transform.html#skimage.transform.iradon Only the filtering part is implemented here; backgrojection is implemented in Sinogram.backproject(), Sinogram.backprojected().

Parameter:

filter_namestr, default=None

Name of a filter to be applied. The recognised values are: “ramp”, “shepp-logan”, “cosine”, “hamming”, “hann”. If None, no filter is applied.

backprojected(interpolation='linear', circle=True, delta_r=2, vmin=None, vmax=None, vfill=None, verbose=False)

Return image reconstructed from sinogram through backprojection.

This method is based on the scikit-image function skimage.transform.iradon(): https://scikit-image.org/docs/stable/api/skimage.transform.html#skimage.transform.iradon Only the backprojection part is implemented here; filtering is implemented in Sinogram.apply_filter(), Sinogram.filtered().

Parameters:

interpolationstr, default=”linear”

Method used to interpolate intensity values at image-slice pixels in backprojection. Recognised methods are: “linear”, “nearest”, “cubic”.

circlebool, default=True

If True, intensity values for pixels outside the inscribed circle in reconstructed image slices are set to the value given by <vfill>.

delta_rfloat, default=2

Tolerance, in voxel units, to be used when whether a voxel is inside the inscribed circle. The nominal circle radius, r, is calculated, and a voxel is considered to be inside the circle if at a radial distance from the centre no greater than r - delta_r.

vminfloat, default=None

Minimum intensity value allowed in the reconstructed image. Any lower intensity values will be set to this value. Setting the minimum can be useful if this is known independently of the sinogram. Applied after assigning <vfill> to voxels outside the inscribed circle of an image slice. Ignored if None.

vmaxfloat, default=None

Maximum intensity value allowed in the reconstructed image. Any higher intensity values will be set to this value. Setting the maximum can be useful if this is known independently of the sinogram. Applied after assigning <vfill> to voxels outside the inscribed circle of an image slice. Ignored if None.

vfillfloat, default=None

Intensity value to be assigned to voxels outside the inscribed circle of an image slice if <circle> is True. If None, set to the image’s minimum intensity value. May be overridden by <vmin> or <vmax>.

verbosebool, default=False

If True, print information on progress in image reconstruction.

filtered(filter_name=None)

Return the result of applying a named filter to sinogram.

A Fourier transform maps a copy of the initial sinogram to the frequency domain, the named filter is applied, and an inverse Fourier transform maps the result back to the spatial domain. The sinogram returned has the same geometry as the original.

The original sinogram is left unaltered. To perform filtering in-place, use: Sinogram.apply_filter().

This method is based on the scikit-image function skimage.transform.iradon(): https://scikit-image.org/docs/stable/api/skimage.transform.html#skimage.transform.iradon Only the filtering part is implemented here; backgrojection is implemented in Sinogram.backproject(), Sinogram.backprojected().

Parameter:

filter_namestr, default=None

Name of a filter to be applied. The recognised values are: “ramp”, “shepp-logan”, “cosine”, “hamming”, “hann”. If None, no filter is applied.

skrt.image.checked_crop_limits(crop_limits=None)

Check input crop limits, returning (xlim, ylim, zlim) tuple that can be passed to skrt.image.Image.crop().

Parameter:

crop_limitsfloat/tuple/list/None default=None

Specification of crop limits:

  • If a float or a one-element tuple or list, crop limits along each axis are taken to be minus and plus the value given.

  • If a three-element tuple or list, the three elements are taken to correspond to x, y, z limits; an element that is a float or a one-element tuple or list is taken to indicate limits along the relevant axis of minus and plus the value given.

  • For all other inputs, a value of (None, None, None) is returned.

skrt.image.crop_by_amounts(obj, dx=None, dy=None, dz=None)

Crop image or ROI by the amounts dx, dy, dz in mm.

Parameters:

objskrt.image.Image/skrt.structures.ROI

Object (Image or ROI) for which cropping is to be performed.

dxfloat/tuple, default=None

Amount(s) by which to crop object in x-direction. If dx is a float, the object is cropped by this amount on both sides. If dx is a tuple, the object is cropped on the sides at lower and higher x by the amounts of the tuple’s first and second elements. No cropping is performed for a crop amount set to None.

dyfloat/tuple, default=None

Amount(s) by which to crop object in y-direction. If dy is a float, the object is cropped by this amount on both sides. If dy is a tuple, the object is cropped on the sides at lower and higher y by the amounts of the tuple’s first and second elements. No cropping is performed for a crop amount set to None.

dzfloat/tuple, default=None

Amount(s) by which to crop object in z-direction. If dz is a float, the object is cropped by this amount on both sides. If dz is a tuple, the object is cropped on the sides at lower and higher z by the amounts of the tuple’s first and second elements. No cropping is performed for a crop amount set to None.

skrt.image.default_aspect()
skrt.image.downsample(data, dx=None, dy=None, dz=None)

Downsample an array by the factors specified in <dx>, <dy>, and <dz>.

skrt.image.entropy(p, base=2)

Calculate entropy for variable(s) from probability distribution.

Parameters:

pnumpy.array

One-dimensional numpy array representing the probabilities of different values of a random variable, or the joint probabilities of different combinations ov values of a set of random variables.

baseint/None, default=2

Base to use when taking logarithms. If None, use base e.

skrt.image.get_alignment_strategy(alignment=None)

Extract information defining strategy for image alignment.

alignmenttuple/dict/str, default=None

Strategy to be used for image alignment. For defailts, see documentation of skrt.image.get_alignment_translation().

skrt.image.get_alignment_translation(im1, im2, alignment=None)

Determine translation for aligning <im1> to <im2>, based on <alignment>.

Parameters:

im1skrt.image.Image

Image that is to be translated to achieve the alignment.

im2skrt.image.Image

Image with which alignment is to be performed.

alignmenttuple/dict/str, default=None

Strategy to be used for image alignment. This can be translation-based, image-based or ROI-based.

  • Translation-based initial alignment: This is specified by: - A tuple indicating the amounts (dx, dy, dz) by which a

    point in <im1> must be translated to align with the corresponding point in <im2>;

  • Image-based alignment: This can be specified by: - A dictionary indicating how <im1> and <im2> are

    to be aligned along each axis, where keys are axis identifiers (‘x’, ‘y’, ‘z’), and values are the types of alignment: - 1: align on lowest coordinates (right, posterior, inferior); - 2: align on centre coodinates; - 3: align on highest coordinates (left, anterior, superior). If an axis isn’t included in the dictionary, or is included with an invalid alignment type, the alignment type defaults to 2.

    • One of the strings “_top_”, “_centre_”, “_bottom_”, in which case <im1> and <im2> have their (x, y) centres aligned, and have z positions aligned at image top, centre or bottom.

  • ROI-based alignment: This defines a translation of <im1> so that an ROI associated with <im1> is aligned with an ROI associated with <im2>. For each image, the alignment point is defined by an ROI name and an optional position. If the optional position is omitted or is None, the alginment point is the centroid of the ROI as a whole. Otherwise, the alignment point is the centroid of an (x, y) slice through the ROI at the specified relative position along the z-axis. This relative position must be in the interval [0, 1], where 0 corresponds to the most-inferior point (lowest z) and 1 corresponds to the most-superior point (highest z).

    The full ROI-based alignment specification is a tuple of two two-element tuples: ((“im1_roi_name”, im1_roi_position), (“im2_roi_name”, im2_roi_position)). If a position is omitted, it defaults to None, and the ROI name can be given either as a string or as a one-element tuple. If information is given only for <im1>, the same information is used for <im2>.

    The following are examples of valid ROI-based alignment specifications, and how they’re interpreted:

    • “roi”: align “roi” of <im1> with “roi” of <im2>, aligning on volume centroids;

    • (“roi1”, “roi2”): align “roi1” of <im1> with “roi2” of <im2>, aligning on volume centroids;

    • (“roi”, 1): align “roi” of <im1> with “roi” of <im2>, aligning on centroids of top slices;

    • ((“roi1”, 0.75), “roi2”): align “roi1” of <im1> with “roi2” of <im2>, aligning centroid of slice three quarters of the way up “roi1” with the volume centroid of “roi2”.

    Note that ROI-based alignment relies on the named ROIs being contained in structure sets associated with <im1> and <im2>. Association of structure sets to images may be performed automatically when loading DICOM data to Patient objects, or may be performed manually using an Image object’s set_structure_set() method.

skrt.image.get_box_mask_from_mask(image=None, dx=0, dy=0)

Slice by slice, create box masks enclosing an arbitrarily shaped mask.

Parameters:

imageImage, default=None

Image object representing arbitrarily shaped mask for which slice-by-slice box masks are to be determined.

dxint, default=0

Margin along columns to be added on each side of mask bounding box.

dyint, default=0

Margin along rows to be added on each side of mask bounding box.

skrt.image.get_dicom_affine(ds, image_positions=None)

Assemble affine matrix from a dicom file. Optionally infer slice thickness from the positions of different slices and origin from the minimum slice; otherwise, extract slice thickness and origin directly from the dicom dataset.

Parameters:

dspydicom.FileDataset

Dicom dataset from which to load voxel sizes.

image_positionsdict, default=None

Dict of 3D origins for each slice, where keys are slice positions and values are origins.

Returns:

affinenp.ndarray

3x3 array containing the affine matrix for this image.

skrt.image.get_dicom_orientation(ds)

Extract and parse image orientation from a dicom file.

Parameters:

dspydicom.FileDataset

Dicom dataset object from which the orientation vector should be read.

Returns:

orientation: np.ndarray

Direction cosines of the first row and first column, reshaped to (2, 3) such that the top row of the array contains the row direction cosine, and the bottom row contains the column direction cosine.

axeslist

List of the axes (x = 0, y = 1, z = 2) corresponding to each image array axis in order [row, column, slice].

skrt.image.get_dicom_paths(path)

Get list of dicom files correpsonding to a single dicom image.

Parameters:

pathstr

Path to either a single dicom file, or a directory containing multiple dicom files.

If path is a directory, a list of dicom files within that directory will be returned.

If path is a single file, that file will be opened and its ImagesInAcquisition property will be checked.

  • If ImagesInAcquisition == 1, a list containing the single input

path will be returned. - Otherwise, a list containing all the dicom files in the same directory as the input file will be returned.

Returns:

pathslist of strs

List of strings, each pointing to a single dicom file. If no valid dicom files are found, returns an empty list.

skrt.image.get_dicom_voxel_size(ds)

Get voxel sizes from a dicom file.

Parameters:

dspydicom.FileDataset

Dicom dataset from which to load voxel sizes.

Returns:

voxel_sizelist

List of voxel sizes in order [row, column, slice].

skrt.image.get_dicom_window(ds)

Get intensity window defaults from a dicom file.

Parameters: ds : pydicom.FileDataset

Dicom dataset from which to read intensity window info.

Returns:

window_centrefloat

Default window centre.

window_widthfloat

Default window width.

skrt.image.get_geometry(affine, voxel_size, origin, is_nifti=False, shape=None)

Get an affine matrix, voxel size list, and origin list from a combination of these inputs.

skrt.image.get_image_comparison_metrics()

Get list of image-comparison metrics.

This returns the combined list of metrics based on mutual information (returned by get_mi_metrics()) and quality metrics (returned by get_quality_metrics()).

skrt.image.get_mask(mask=None, mask_threshold=0.5, image_to_match=None)

Return mask as Image object, with boolean data, resizing if required.

Parameters:

maskImage/list/ROI/str/StructureSet, default=None

Image object representing a mask or a source from which an Image object can be initialised. In addition to the sources accepted by the Image constructor, the source may be an ROI, a list of ROIs or a StructureSet. In the latter cases, the mask image is derived from the ROI mask(s).

mask_thresholdfloat, default=0.5

Threshold for mask data. Values above and below this value are set to True and False respectively. Taken into account only if the mask image has non-boolean data.

image_to_matchImage/str, default=None

Image object or a source from which an Image object can be initialised. The mask will be resized if needed, to match this image.

skrt.image.get_mask_bbox(mask)

Obtain bounding box of labelled area of label mask.

The bounding box is returned as [(xmin, xmax), (ymin, ymax), (zmin, zmax)], with values in mm.

Parameter:

maskskrt.image.Image

Image object representing label mask for which bounding box is to be obtained.

skrt.image.get_mi_metrics()

Get list of metrics based on mutual information.

All metrics listed here should be recognised by Image.get_mutual_information(), and all metrics recognised by Image.get_mutual_information() should be listed here.

skrt.image.get_quality_metrics()

Get list of metrics measuring quality of one metric relative to another.

All metrics listed here should be recognised by Image.get_quality(), and all metrics recognised by Image.get_quality() should be listed here.

skrt.image.get_translation_to_align(im1, im2, alignments=None, default_alignment=2, threshold=None)

Determine translation for aligning <im1> to <im2>.

Parameters:

im1skrt.image.Image

Image that is to be translated to achieve the alignment.

im2skrt.image.Image

Image with which alignment is to be performed.

alignmentsdict, default=None

Dictionary indicating how alignment is to be performed along each axis, where keys are axis identifiers (‘x’, ‘y’, ‘z’), and values are the types of alignment. The valid alignment values are: - 1: align on lowest coordinates (right, posterior, inferior); - 2: align on centre coodinates; - 3: align on highest coordinates (left, anterior, superior). If an axis isn’t included in the dictionary, or is included with an invalid alignment type, the value of <default_alignment> is used for this axis.

default_alignmentint, default=2

Type of alignment to be applied along any axis not included in the <alignments> dictionary.

thresholdint/float, default=None

If None, alignment is with respect to the whole images. If an integer or float, alignment is with respect to the masks returned for the images by skrt.image.Image.get_foreground_mask(), using value specified as the threshold parameter for mask creation.

skrt.image.get_translation_to_align_image_rois(im1, im2, roi_name1, roi_name2, z_fraction1=None, z_fraction2=None)

Determine translation for aligning ROI of <im1> to ROI of <im2>.

Parameters:

im1skrt.image.Image

Image with linked StructureSet containing ROI to be translated to achieve the alignment.

im2skrt.image.Image

Image with linked StructureSet containing ROI with which alignment is to be performed.

roi_name1str

Name of ROI contained in StructureSet linked to <im1>, and that it to be translated to achieve the alignment.

roi_name2str

Name of ROI contained in StructureSet linked to <im2>, and with which alignment is to be performed.

z_fraction1float, default=None

For ROI identified by <roi_name1>, position along z axis of iROI slice on which to align. If None, alignment is to the centroid of the whole ROI volume. Otherwise, alignment is to the centroid of the slice at the specified distance from the ROI’s most-inferior point: 0 corresponds to the most-inferior point (lowest z); 1 corresponds to the most-superior point (highest z). Values for z_fraction outside the interval [0, 1] result in a RuntimeError.

z_fraction2float, default=None

For ROI identified by <roi_name2>, position along z axis of ROI slice on which to align. If None, alignment is to the centroid of the whole ROI volume. Otherwise, alignment is to the centroid of the slice at the specified distance from the ROI’s most-inferior point: 0 corresponds to the most-inferior point (lowest z); 1 corresponds to the most-superior point (highest z). Values for z_fraction outside the interval [0, 1] result in a RuntimeError.

skrt.image.kv_to_mv(hu)

Map radiodensity in Hounsfield units from kV CT scan to MV CT scan.

Function originally written by M.Z. Wilson. Parameterisation derived from kV and MV CT scans collected in VoxTox study.

Parameter:

hu - int

Radiodensity (Hounsfield units) for kV CT scan.

skrt.image.load_dicom(paths, debug=False)

Load a dicom image from one or more dicom files.

Parameters:

pathsstr/list

Path to a single dicom file, path to a directory containing multiple dicom files, or list of paths to dicom files. If path points to a single file that is found to be part of a series of multiple dicom files corresponding to one image, the image will be loaded from all dicom files in the same directory as the first that match its StudyInstanceUID and SeriesNumber.

Returns:

datanp.ndarray

Numpy array containing the voxel intensities for the image.

affinenp.ndarray

3x3 numpy array containing the affine matrix.

window_centrefloat

Default intensity window centre for viewing this image.

window_widthfloat

Default intensity window width for viewing this image.

dspydicom.FileDataset

Dicom dataset corresponding to the last file loaded.

z_pathsdict / None

Dictionary mapping z slice positions in mm to the file corresponding to that slice. If image was loaded from a single file, this will be None.

z_instance_numbersdict / None

Dictionary mapping z slice positions in mm to the instance number of that slice. If image was loaded from a single file, this will be None.

skrt.image.load_dicom_many_files(paths)

Load an image array from multiple dicom files and use the spacing between slices to determine the slice thickness.

Parameters:

pathslist of strs

List of paths to the dicom files from which the image should be loaded.

Returns:

imagenp.ndarray

Numpy array containing image data.

affinenp.ndarray

3x3 numpy array containing affine matrix.

dspydicom.FileDataset

Dataset object corresponding to the last file loaded.

z_pathsdict

Dict mapping z slice positions in mm to the filepath from which that slice of the image was read.

z_instance_numbersdict

Dict mapping z slice positions in mm to the instance number of that slice of the image.

skrt.image.load_dicom_single_file(path)

Load an image array from a single dicom file.

Parameters:

pathstr

Path to the dicom file from which the image should be loaded.

Returns:

imagenp.ndarray

Numpy array containing image data.

affinenp.ndarray

3x3 numpy array containing affine matrix.

dspydicom.FileDataset

Dataset object corresponding to the dicom file.

skrt.image.load_nifti(path)

Load an image from a nifti file.

skrt.image.load_npy(path)

Load a numpy array from a .npy file.

skrt.image.load_rgb(path, rgb_weights=(0.299, 0.587, 0.114), rgb_rescale_slope=100, rgb_rescale_intercept=0)

Load an rgb image with the Python Imaging Library (PIL), and convert to grey levels.

Parameter:

rgb_weightstuple, default=(0.299, 0.587, 0.114)

Three-element tuple specifying the weights to red (R), green (G), blue (B) channels to arrive at a grey level:

L = R * rgb[0] + G * rgb[1] + B * rgb[2]

The default is the same as the PIL default: https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.convert

rgb_rescale_slope: float, default=100

Factor by which to multiply grey level in rescaling.

rgb_rescale_intercept: float, default=0

Constant to add to multiplied grey level in rescaling.

skrt.image.match_image_voxel_sizes(im1, im2, voxel_size=None, order=1)

Resample pair of images to same voxel size.

Parameters:

im1, im2skrt.image.Image

Images to resample.

voxel_sizetuple/str/float, default=None

Specification of voxel size for image resampling. Possible values are:

  • None: no resampling performed;

  • “dz_max”: the image with smaller slice thickness is resampled to have the same voxel size as the image with larger slice thickness;

  • “dz_min”: the image with larger slice thickness is resampled to have the same voxel size as the image with smaller slice thickness;

  • (dx, dy, dz): both images are resampled, to have voxels with the specified dimensions in mm.

  • dxyz: both images are resampled, to have voxels with the specified dimension in mm along all axes.

order: int, default = 1

Order of the b-spline used in interpolating voxel intensity values.

skrt.image.match_images(im1, im2, ss1=None, ss2=None, ss1_index=-1, ss2_index=-1, ss1_name=None, ss2_name=None, roi_names=None, im2_crop_focus=None, im2_crop_margins=None, im2_crop_about_centre=False, alignment=None, voxel_size=None, bands=None)

Process pair of images, so that they match in one or more respects.

Matching can be with respect to image size, voxel size, grey-level banding, and/or ROI naming in associated structure sets. The returned images are created from clones of the input images, which are left unchanged.

The second ROI of the pair may be cropped about a focus (ROI or point). The first ROI of the pair may be cropped to the size of the first.

Parameters:

im1, im2skrt.image.Image

Images to be matched with one another.

ss1, ss2skrt.structures.StructureSet, default=None

Structure sets to associate with images im1, im2. If a value is None, and image matching involves ROI alignment, a structure set already associated with the relevant image is used (im1.structure_sets[ss1_index], im2.structure_sets[ss2_index]).

ss1_index, ss2_indexint, default=-1

Structure set indices to use for ROI alignment based on structure sets already associated with images.

ss1_name, ss2_namestr, default=None

Names to be assigned to structure sets associated with the returned image objects. If a value is None, the original name is kept.

roi_namesdict, default=None

Dictionary for renaming and filtering ROIs for inclusion in the structure sets associated with the output images. Keys are names for ROIs to be kept, and values are lists of alternative names with which these ROIs may have been labelled in the input structure sets. The alternative names can contain wildcards with the ‘*’ symbol. If a value of None is given, all ROIs in the input structure sets are kept, with no renaming.

im2_crop_focusstr/tuple, default=None

Name of an ROI, or (x, y, z) coordinates of a point, about which to perform cropping of im2. If None, cropping is performed about the point (0, 0, 0) if im2_crop_margins is non-null, or otherwise no cropping is performed.

im2_crop_margins, float/tuple, default=None

Specification of margin around focus for cropping of im2. For information on specifying crop margins for the case where im2_crop_focus is the name of an ROI, see documentation for method skrt.image.Image.crop_to_roi(). For the case where im2_crop_focus is a point coordinate, margins should be sepecified by a tuple (xlim, ylim, zlim). Here, xlim, ylim, zlim are two-component tuples specifying lower and upper bounds relative to the crop point.

im2_crop_about_centre: bool, default=False

For the case where im2_crop_focus is the name of an ROI: if True, im2 is cropped to the centre point of the ROI plus margins; if False, im2 is cropped to the ROI extents plus margins. Ignored for the case where im2_crop_focus isn’t the name of an ROI.

alignmenttuple/dict/str, default=None

Strategy to be used for aligning images prior to cropping so that they have the same size. For strategy details, see documentation of skrt.image.get_alignment_translation(). After alignment, im1 is cropped to the size of im2, then im2 is cropped to the size of im1. To omit cropping to the same size, set alginment to False.

voxel_sizetuple/str/float, default=None

Specification of voxel size for image resampling. For possible values, see documentation for function skrt.image.match_image_voxel_size().

bands - dict, default=None

Dictionary of value bandings to be applied to image data. Keys specify band limits, and values indicte the values to be assigned. For more information, see documentation of method skrt.image.Image.apply_banding().

skrt.image.match_images_for_comparison(im1, im2, ss1=None, ss2=None, ss1_index=-1, ss2_index=-1, ss1_name=None, ss2_name=None, roi_names=None, alignment=None, voxel_size=None)

Process pair of images, to allow their comparison.

Images are optionally aligned, then their geometries are matched, so that they can be handled by the image-comparison methods Image.get_comparison() and Image.get_quality().

This function provides a subset of the processing options offered by match_images(), and in addition can change the origin of the first image, to align better with the second image.

Parameters:

im1, im2skrt.image.Image

Images to be matched for comparison.

ss1, ss2skrt.structures.StructureSet, default=None

Structure sets to associate with images im1, im2. If a value is None, and image matching involves ROI alignment, a structure set already associated with the relevant image is used (im1.structure_sets[ss1_index], im2.structure_sets[ss2_index]).

ss1_index, ss2_indexint, default=-1

Structure set indices to use for ROI alignment based on structure sets already associated with images.

ss1_name, ss2_namestr, default=None

Names to be assigned to structure sets associated with the returned image objects. If a value is None, the original name is kept.

roi_namesdict, default=None

Dictionary for renaming and filtering ROIs for inclusion in the structure sets associated with the output images. Keys are names for ROIs to be kept, and values are lists of alternative names with which these ROIs may have been labelled in the input structure sets. The alternative names can contain wildcards with the ‘*’ symbol. If a value of None is given, all ROIs in the input structure sets are kept, with no renaming.

alignmenttuple/dict/str, default=None

Strategy to be used for aligning images prior to cropping so that they have the same size. For strategy details, see documentation of skrt.image.get_alignment_translation(). After alignment, im1 is cropped to the size of im2, then im2 is cropped to the size of im1. To omit cropping to the same size, set alginment to False.

voxel_sizetuple/str/float, default=None

Specification of voxel size for image resampling. For possible values, see documentation for function skrt.image.match_image_voxel_size().

skrt.image.pad_transpose(transpose, ndim)

Pad a transpose vector to match a given number of dimensions.

skrt.image.remove_duplicate_images(images=None)

Remove duplicates from a list of image objects.

Image instance image1 is taken to be a duplicate of image2 if image1.has_same_data(image2) is True.

Parameter: images: list, default=None

List of image objects, from which duplicates are to be removed.

skrt.image.rescale_dicom_data(ds, data)

Rescale an array according to rescaling info in a dicom dataset.

Parameters:

dspydicom.FileDataset

Dicom dataset from which to read rescaling info.

datanp.ndarray

Image array to be rescaled.

Returns:

datanp.ndarray

Rescaled version of the input array

skrt.image.rescale_images(images, v_min=0.0, v_max=1.0, constant=0.5, clone=True)

For one or more images, linearly rescale greyscale values so that they span a specified range.

Returns the input images if no rescaling is performed. Otherwise returns the input images rescaled (<clone> set to False) or rescaled clones of the input images (<clone> set to True).

imagelist

List of skrt.image.Image objects, for which rescaling is to be performed.

v_min: float, default=0.0

Minimum greyscale value after rescaling. If None, no rescaling is performed.

v_max: float, default=1.0

Maximum greyscale value after rescaling. If None, no rescaling is performed.

constant: float, default=0.5

Greyscale value to assign after rescaling if all values in the original image are the same. If None, original value is kept.

clonebool, default=True

If True, clone each input image before rescaling.

skrt.image.set_ax(obj, view=None, ax=None, gs=None, figsize=None, zoom=None, colorbar=False, aspect_getter=<function default_aspect>, **kwargs)

Set up axes for plotting an object, either from a given exes or gridspec, or by creating new axes.

skrt.image.set_image_orientation_patient(ds)

Try to ensure that image orientation patient is set for DICOM dataset.

If the dataset doesn’t have the attribute ImageOrientationPatient, the effective value is determined from PatientOrientation, if present.

Parameter:

dspydicom.FileDataset

DICOM dataset.

skrt.image.sum_images(images=None)

Sum images of the same geometry.

If not all images have the same same geometry (shape, origin, voxel size), None is returned. Otherwise, an Image object is returned that has the same geometry as the input images, and where array values are the sums of the array values of the input images.

Parameter: images: list, default=None

List of Image objects to be summed.

skrt.image.to_inches(size)

Convert a size string to a size in inches. If a float is given, it will be returned. If a string is given, the last two characters will be used to determine the units:

  • ‘in’: inches

  • ‘cm’: cm

  • ‘mm’: mm

  • ‘px’: pixels

skrt.image.write_nifti(outname, data, affine)

Create a nifti file at <outname> containing <data> and <affine>.

skrt.image.write_npy(outname, data, affine=None)

Create numpy file containing data. If <affine> is not None, voxel sizes and origin will be written to a text file.