skrt.structures module

Classes related to ROIs and structure sets.

class skrt.structures.ROI(source=None, name=None, color=None, load=True, image=None, shape=None, affine=None, voxel_size=None, origin=None, mask_threshold=0.25, default_geom_method='auto', overlap_level=None, alpha_over_beta=None, **kwargs)

Bases: Archive

Class representing a single region of interest (ROI).

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

__init__(source=None, name=None, color=None, load=True, image=None, shape=None, affine=None, voxel_size=None, origin=None, mask_threshold=0.25, default_geom_method='auto', overlap_level=None, alpha_over_beta=None, **kwargs)

Load ROI from mask or contour.

Parameters:

sourcestr/array/nifti, default=None

Source of image data to load. Can be either:

  1. The path to a nifti file containing a binary mask;

  2. A numpy array containing a binary mask;

  3. The path to a file containing a numpy array;

  4. The path to a dicom structure set file.

  5. Dictionary of contours in the x-y orientation, where the keys are z positions in mm and values are lists of lists of 3D contour points in order (x, y, z) or 2D contour points in order (x, y) on each slice.

  6. Dictionary of shapely polygons and/or multipolygons in the x-y orientation, where the keys are z positions in mm and values are lists of polygons/multipolygons on each slice.

namestr, default=None

Name of the ROI. If <source> is a file and no name is given, the name will be inferred from the filename.

colormatplotlib color, default=None

Color in which this ROI will be plotted. If None, a color will be assigned.

loadbool, default=True

If True, contours/mask will be created during initialisation; otherwise they will be created on-demand.

imageImage/str, default=None

Associated image from which to extract shape and affine matrix. Can either be an existing Image object, or a path from which an Image can be created.

shapelist, default=None

Number of voxels in the image to which the ROI belongs, in order (x, y, z); needed to create mask if contours are provided in <source> but no associated <image> is assigned.

affinenp.ndarray, default=None

Affine matrix of the image to which the ROI belongs. Needed to create mask if contours are provided in <source> but no associated <image> is assigned, and no <voxel_size> and <origin> are given. If <affine> is given, it supercedes the latter two arguments.

voxel_sizetuple, default=(1, 1, 1)

Voxel sizes in mm in order (x, y, z); used if <affine> and <image> are not provided.

origintuple, default=(0, 0, 0)

Origin position in mm in order (x, y, z); used if <affine> and <image> are not provided.

mask_thresholdfloat, default=0.25

Used if the ROI is created from a non-boolean pixel array. Values in the array exceeding this level are taken to be inside the ROI when it is converted to a boolean array.

default_geom_methodstr, default=”auto”

Default method for computing geometric quantities (area, centroid, etc). Can be any of:

  1. “contour”: geometric quantities will be calculated from Shapely polygons made from contour points.

  2. “mask”: geometric quantities will be calculated from numpy array representing a binary mask.

  3. “auto”: the “contour” or “mask” method will be used, depending on whether the input that create the ROI comprised of contours or an array, respectively.

overlap_levelfloat, default=None

Used when converting an input ROI contour to a mask; required overlap of a pixel with the ROI contour in order for the pixel to be added to the mask. If None, the output of skimage.draw.polygon2mask will be returned with no border checks, which is faster than performing border checks.

alpha_over_betafloat, default=None

Ratio for ROI tissue of coefficients, alpha, beta, of linear-quadratic equation. This ratio is used in calculating biologically effective dose, BED, from physical dose, D, delivered over n equal fractions:

BED = D * (1 + (D/n) / (alpha/beta)).

If None, the biologically effective dose is taken to be equal to the physical dose (beta >> alpha).

kwargsdict, default=None

Extra arguments to pass to the initialisation of the parent Image object.

add_plan(plan)

Add a Plan object to be associated with this ROI. This does not affect the structure set associated with the Plan object.

Parameters:

planskrt.dose.Plan

A Plan object to assign to this structure set.

add_rois(rois)

Add ROI(s) to this ROI.

This method returns the result of the addition. The original ROIs are left unaltered.

Parameter:

rois: ROI/StructureSet/list

ROI(s) to be added. This can be a single ROI, a StructureSet, or a list of ROI/StructureSet objects.

clear_plans()

Clear all plan maps associated with this ROI.

clone_attrs(obj, copy_data=True)

Assign all attributes of <self> to another object, <obj>, ensuring that own mask’s data gets correctly copied if <copy_data> is True.

create_contours(view='all', force=False)

Create contours in all orientations.

create_mask(force=False, overlap_level=None, voxel_size=None, shape=None)

Create binary mask representation of this ROI. If the ROI was created from contours, these contours will be converted to a mask; if the ROI was created from a mask, this mask will be cast to a boolean array and its geoemtric properties will be assigned to this ROI. If a mask has already been created, nothing will happen unless force=True.

Parameters:

forcebool, default=False

If True, the mask will be recreated even if it already exists.

overlap_levelfloat, default=0.25

Required overlap of a pixel with the ROI contour in order for the pixel to be added to the mask. If None, the value of self.overlap_level will be used; otherwise, self.overlap_level will be overwritten with this value. If both are None, the output of skimage.draw.polygon2mask will be returned with no border checks, which is faster than performing border checks.

voxel_sizelist, default=None

Voxel sizes of the desired mask in the [x, y] direction. Only used if the ROI was created from contours; ignored if ROI was created from mask. Causes self.image to be replaced with a blank dummy image with these voxel sizes.

shapelist, default=None

Shape of the desired mask in the [x, y] direction. Only used if <voxel_size> is None and the ROI was created from contours; ignored if ROI was created from mask. Causes self.image to be replaced with a blank dummy image of this shape.

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

Crop ROI to specified range in x, y, z.

Parameters:

xlimtuple, default=None

Lower and upper bounds in mm for cropping along x-axis. If set to None, no cropping is performed. If a bound is set to None, that bound is disregarded.

ylimtuple, default=None

Lower and upper bounds in mm for cropping along y-axis. If set to None, no cropping is performed. If a bound is set to None, that bound is disregarded.

zlimtuple, default=None

Lower and upper bounds in mm for cropping along z-axis. If set to None, no cropping is performed. If a bound is set to None, that bound is disregarded.

If only zlim is not set to None and the ROI source type is “contour”, cropping is performed by discarding contours outside the required range. Othwise cropping is performed on the ROI mask.

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

Crop ROI 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 ROI is cropped by this amount on both sides; - two-element tuple: the ROI 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_roi(roi, **kwargs)

Crop ROI mask to region covered by an ROI.

crop_to_roi_length(other, ax='z')

Crop to length of other ROI along a given axis.

Parameters: other : skrt.structures.ROI

ROI object to which to crop.

axstr/int, default=”z”

Axis along which to perform cropping. Should be one of [“x”, “y”, “z”] or [0, 1, 2].

flattened(view='x-y')

Obtain ROI flattened across all slices in the specified view. The extents and centroid of the flattened ROI are the same as those of the original.

Parameter:

viewstr, default=”x-y”

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

get_abs_centroid_distance(roi, view='x-y', single_slice=False, flatten=False, sl=None, idx=None, pos=None, units='mm', method=None, force=True, by_slice=None, value_for_none=None, slice_stat=None, slice_stat_kwargs=None)

Get absolute centroid distance with respect to another ROI.

Parameters:

roiROI

Other ROI with which to compare centroid.

viewstr, default=”x-y”

Orientation in which to get centroids if using a single slice or flattening.

single_slicebool, default=False

If True, the centroid will be returned for a single slice.

flattenbool, default=False

If True, the 3D centroid will be obtained and then the absolute value along only the 2D axes in the orientation in <view> will be returned.

slint, default=None

Slice number. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of each ROI will be used.

idxint, default=None

Array index of slice. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of each ROI will be used.

posfloat, default=None

Slice position in mm. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of each ROI will be used.

unitsstr, default=”mm”
Units of absolute centroid distance. Can be any of:
  • “mm”: return centroid position in millimetres.

  • “voxels”: return centroid position in terms of array indices.

  • “slice”: return centroid position in terms of slice numbers.

If units=”voxels” or “slice” is requested but either ROI only has contours and no mask shape/voxel size information, an error will be raised (unless ax=”z”, in which case voxel size will be inferred from spacing between slices).

methodstr, default=None
Method to use for centroid calculation. Can be:
  • “contour”: get centroid of shapely contour(s).

  • “mask”: get average position of voxels in binary mask.

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

forcebool, default=True

If True, the global centroid will always be recalculated; otherwise, it will only be calculated if it has not yet been cached in self._volume. Note that if single_slice=True, the centroid will always be recalculated.

by_slicestr, default=None

If one of “left”, “right”, “union”, “intersection”, calculate Dice scores slice by slice for each slice containing self and/or other:

  • “left”: consider only slices containing self;

  • “right”: consider only slices containing other;

  • “union”: consider slices containing either of self and other;

  • “intersection”: consider slices containing both of self and other.

If slice_stat is None, return a dictionary where keys are slice positions and values are the calculated Dice scores. Otherwise, return for the calculated Dice scores the statistic specified by slice_stat.

value_for_nonefloat, default=None

For single_slice and by_slice, value to be returned for slices where Dice score is undetermined (None). For slice_stat, value to substitute for any None values among the inputs for calculating slice-based statistic. If None in the latter case, None values among the inputs are omitted.

slice_statstr, default=None

Single-variable statistic(s) to be returned for slice-by-slice Dice scores. This should be the name of the function for calculation of the statistic(s) in the Python statistics module:

https://docs.python.org/3/library/statistics.html

Available options include: “mean”, “median”, “mode”, “stdev”, “quantiles”. Disregarded if None.

If by_slice is None and slice_stat is different from None, skrt.core.Defaults().by_slice is used for the former.

slice_stat_kwargsdict, default=None

Keyword arguments to be passed to function of statistics module for calculation relative to slice values. For example, if quantiles are required for 10 intervals, rather than for the default of 4, this can be specified using:

slice_stat_kwargs{“n” : 10}

For available keyword options, see documentation of statistics module at:

https://docs.python.org/3/library/statistics.html

get_added_path_length(other, single_slice=False, view='x-y', sl=None, idx=None, pos=None, method=None, connectivity=2, flatten=False, in_slice=True, voxel_size=None, voxel_dim_tolerance=0.1, by_slice=None, value_for_none=None, slice_stat=None, slice_stat_kwargs=None)

Get added path length with respect to another ROI.

The added path length may be obtained either globally or on a single slice.

Added path length is defined in:

https://doi.org/10.1016/j.phro.2019.12.001

Two methods for estimating added path length are implemented here:

  • From ROI contours, the added path length is estimated as the length of the contours of this ROI minus the lengths of the contour portions that coincide with the contours of the other ROI. The value returned is a length in mm.

  • From ROI binary masks, the added path length is estimated as the number of voxels on the surface of the mask of this ROI minus the number of these voxels that are also on the surface of the other ROI, similar to the approach of:

    https://github.com/kkiser1/Autosegmentation-Spatial-Similarity-Metrics

    The value returned is a number of voxels.

By default, the method used is based on the ROI representation of the ROI source. This is contours for a DICOM source and binary masks for a NIfTI source. The default may be overridden using the <method> parameter.

When estimating added path length from ROI binary masks, the value set for <voxel_size> effectively sets a tolerance on ROI agreement. Added path lengths based on different voxel sizes can’t be directly compared.

Parameters:

otherROI

Other ROI to compare with this ROI.

single_slicebool, default=False

If False, the sum of the added path lengths for all ROI slices will be returned; otherwise, the added path length on a single slice will be returned.

viewstr, default=”x-y”

Orientation of slice on which to get added path length. Only used if single_slice=True. If using, <ax> must be an axis that lies along the slice in this orientation.

slint, default=None

Slice number. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of this ROI will be used.

idxint, default=None

Array index of slice. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of this ROI will be used.

posfloat, default=None

Slice position in mm. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of this ROI will be used.

methodstr, default=None
Method to use for calculation of added path length. Can be:
  • “contour”: compute unshared portions of shapely contours, with result returned in mm.

  • “mask”: compute unshared voxels at surface of binary masks, with result returned as number of voxels.

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

connectivity: int, default=2

Integer defining which voxels to consider as neighbours when performing erosion operation to identify ROI surfaces. This is passed as <connectivity> parameter to: scipy.ndimage.generate_binary_structure For further details, see:

Disregarded when calculation of added path length is from contours.

flattenbool, default=False

If True, all slices for each ROI will be flattened in the given orientation, and surface distances relative to the flattened slice will be returned.

in_slicebool, default=True

If True, only intra-slice connectivity is considered when performing erosion to identify ROI surfaces. Disregarded when calculation of added path length is from contours.

voxel_sizetuple, default=None

Voxel size (dx, dy, dz) in mm to be used for ROI masks from which to calculate surface distances. If None, the mask voxel size of <other> is used. If an individual element is None, the value of the corresponding element for the mask voxel size of <other> is used. Disregarded when calculation of added path length is from contours.

voxel_dim_tolerancefloat, default=0.1

Tolerence used when determining whether <voxel_size> is different from the voxel size of the images associated with each ROI. Disregarded when calculation of added path length is from contours.

by_slicestr, default=None

If one of “left”, “right”, “union”, “intersection”, calculate added path length scores slice by slice for each slice containing self and/or other:

  • “left”: consider only slices containing self;

  • “right”: consider only slices containing other;

  • “union”: consider slices containing either of self and other;

  • “intersection”: consider slices containing both of self and other.

If slice_stat is None, return a dictionary where keys are slice positions and values are the calculated added path lengths. Otherwise, return for the calculated added path lengths the statistic specified by slice_stat.

value_for_nonefloat, default=None

For single_slice and by_slice, value to be returned for slices where added path lenght is undetermined. For slice_stat, value to substitute for any None values among the inputs for calculating slice-based statistic. If None in the latter case, None values among the inputs are omitted.

slice_statstr, default=None

Single-variable statistic(s) to be returned for slice-by-slice added path lengths. This should be the name of the function for calculation of the statistic(s) in the Python statistics module:

https://docs.python.org/3/library/statistics.html

Available options include: “mean”, “median”, “mode”, “stdev”, “quantiles”. Disregarded if None.

If by_slice is None and slice_stat is different from None, the former defaults to “union”.

slice_stat_kwargsdict, default=None

Keyword arguments to be passed to function of statistics module for calculation relative to slice values. For example, if quantiles are required for 10 intervals, rather than for the default of 4, this can be specified using:

slice_stat_kwargs{“n” : 10}

For available keyword options, see documentation of statistics module at:

https://docs.python.org/3/library/statistics.html

get_affine(force_standardise=False, **kwargs)

Load self and get affine matrix.

get_alpha_over_beta()

Get ratio for ROI tissue of coefficients of linear-quadratic equation.

get_area(view='x-y', sl=None, idx=None, pos=None, units='mm', method=None, flatten=False)

Get the area of the ROI on a given slice.

Parameters:

viewstr, default=”x-y”

Orientation of slice for which to get area.

slint, default=None

Slice number. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of the ROI will be used.

idxint, default=None

Array index of slice. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of the ROI will be used.

posfloat, default=None

Slice position in mm. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of the ROI will be used.

unitsstr, default=”mm”

Units of area. Can be either of:

  • “mm”: return area in millimetres squared.

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

If units=”voxels” is requested but this ROI only has contours and no voxel size information, an error will be raised.

methodstr, default=None

Method to use for area calculation. Can be:

  • “contour”: compute area from shapely polygon on the slice.

  • “mask”: compute area by summing pixels on the slice and multiplying by the area of one pixel.

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

flattenbool, default=False

If True, all slices will be flattened in the given orientation and the area of the flattened slice will be returned. Only available if method=”mask”.

get_area_diff(other, view='x-y', sl=None, idx=None, pos=None, units='mm', method=None, flatten=False, by_slice=None, slice_stat=None, value_for_none=None, **slice_stat_kwargs)

Get absolute area difference between two ROIs.

get_area_ratio(other, view='x-y', sl=None, idx=None, pos=None, units='mm', method=None, flatten=False, by_slice=None, slice_stat=None, value_for_none=None, **slice_stat_kwargs)

Get ratio of another ROI’s area with respect to own area.

get_aspect_ratio(view, *args, **kwargs)

Get aspect ratio for this structure in a given orientation.

get_bbox_centre_and_widths(buffer=None, buffer_units='mm', method=None)

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

Method parameters are passed to skrt.structures.ROI.get_extents() to obtain ROI extents. For parameter explanations, see skrt.structures.ROI.get_extents() documentation.

get_centre(view='x-y', single_slice=False, sl=None, idx=None, pos=None, method=None)

Get centre position in 2D or 3D in mm.

get_centroid(view='x-y', single_slice=False, sl=None, idx=None, pos=None, units='mm', method=None, force=True)

Get either 3D global centroid position or 2D centroid position on a single slice. If single_slice=False, the calculated global centroid will be cached in self._centroid[units] and returned if called again, unless force=True.

Parameters:

single_slicebool, default=False

If False, the global 3D centroid of the entire ROI will be returned; otherwise, the 2D centroid on a single slice will be returned.

viewstr, default=”x-y”

Orientation of slice on which to get centroid. Only used if single_slice=True. If using, <ax> must be an axis that lies along the slice in this orientation.

slint, default=None

Slice number. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of the ROI will be used.

idxint, default=None

Array index of slice. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of the ROI will be used.

posfloat, default=None

Slice position in mm. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of the ROI will be used.

unitsstr, default=”mm”
Units of centroid. Can be either of:
  • “mm”: return centroid position in millimetres.

  • “voxels”: return centroid position in terms of array indices.

  • “slice”: return centroid position in terms of slice numbers.

If units=”voxels” or “slice” is requested but this ROI only has contours and no mask shape/voxel size information, an error will be raised (unless ax=”z”, in which case voxel size will be inferred from spacing between slices).

methodstr, default=None
Method to use for centroid calculation. Can be:
  • “contour”: get centroid of shapely contour(s).

  • “mask”: get average position of voxels in binary mask.

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

forcebool, default=True

If True, the global centroid will always be recalculated; otherwise, it will only be calculated if it has not yet been cached in self._volume. Note that if single_slice=True, the centroid will always be recalculated.

get_centroid_distance(roi, single_slice=False, view='x-y', sl=None, idx=None, pos=None, units='mm', method=None, force=True, by_slice=None, value_for_none=None, slice_stat=None, **slice_stat_kwargs)

Get centroid displacement vector with respect to another ROI.

Parameters:

roiROI

Other ROI with which to compare centroid.

single_slicebool, default=False

If True, the centroid will be returned for a single slice.

viewstr, default=”x-y”

Orientation in which to get centroids if using a single slice or flattening.

flattenbool, default=False

If True, the 3D centroid will be obtained and then the absolute value along only the 2D axes in the orientation in <view> will be returned.

slint, default=None

Slice number. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of each ROI will be used.

idxint, default=None

Array index of slice. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of each ROI will be used.

posfloat, default=None

Slice position in mm. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of each ROI will be used.

unitsstr, default=”mm”
Units of absolute centroid distance. Can be any of:
  • “mm”: return centroid position in millimetres.

  • “voxels”: return centroid position in terms of array indices.

  • “slice”: return centroid position in terms of slice numbers.

If units=”voxels” or “slice” is requested but either ROI only has contours and no mask shape/voxel size information, an error will be raised (unless ax=”z”, in which case voxel size will be inferred from spacing between slices).

methodstr, default=None
Method to use for centroid calculation. Can be:
  • “contour”: get centroid of shapely contour(s).

  • “mask”: get average position of voxels in binary mask.

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

forcebool, default=True

If True, the global centroid will always be recalculated; otherwise, it will only be calculated if it has not yet been cached in self._volume. Note that if single_slice=True, the centroid will always be recalculated.

by_slicestr, default=None

If one of “left”, “right”, “union”, “intersection”, calculate Dice scores slice by slice for each slice containing self and/or other:

  • “left”: consider only slices containing self;

  • “right”: consider only slices containing other;

  • “union”: consider slices containing either of self and other;

  • “intersection”: consider slices containing both of self and other.

If slice_stat is None, return a dictionary where keys are slice positions and values are the calculated Dice scores. Otherwise, return for the calculated Dice scores the statistic specified by slice_stat.

value_for_nonefloat, default=None

For single_slice and by_slice, value to be returned for slices where Dice score is undetermined (None). For slice_stat, value to substitute for any None values among the inputs for calculating slice-based statistic. If None in the latter case, None values among the inputs are omitted.

slice_statstr, default=None

Single-variable statistic(s) to be returned for slice-by-slice Dice scores. This should be the name of the function for calculation of the statistic(s) in the Python statistics module:

https://docs.python.org/3/library/statistics.html

Available options include: “mean”, “median”, “mode”, “stdev”, “quantiles”. Disregarded if None.

If by_slice is None and slice_stat is different from None, skrt.core.Defaults().by_slice is used for the former.

slice_stat_kwargsdict, default=None

Keyword arguments to be passed to function of statistics module for calculation relative to slice values. For example, if quantiles are required for 10 intervals, rather than for the default of 4, this can be specified using:

slice_stat_kwargs{“n” : 10}

For available keyword options, see documentation of statistics module at:

https://docs.python.org/3/library/statistics.html

get_color_from_kwargs(kwargs={}, key='roi_colors')

Return ROI colour passed via dictionary of keyword arguments.

Parameters:

kwargsdict, default={}

Dictionary of keyword arguments, which may include parameter providing dictionary of ROI colours for plotting.

keystr, default=’roi_colors’

Key in kwargs dictionary specifying parameter that, if present, provides dictionary of ROI colours.

get_comparison(roi, metrics=None, vol_units='mm', area_units='mm', centroid_units='mm', view='x-y', sl=None, pos=None, idx=None, method=None, slice_stats=None, default_by_slice=None, units_in_header=False, global_vs_slice_header=False, name_as_index=True, nice_columns=False, decimal_places=None, force=True, voxel_size=(1, 1, 1), match_lengths=False, match_lengths_strategy=1)

Return a pandas DataFrame of the comparison metrics listed in <metrics> with respect to another ROI.

Parameters:

roiROI

Other ROI with which to compare this ROI.

metricslist, default=None

List of metrics to include in the table. Options:

  • “dice” : global Dice score.

  • “dice_flat”: Dice score of ROIs flattened in the orientation specified in <view>.

  • “dice_slice”: Dice score on a single slice.

  • “dice_slice_stats”: statistics specified in <slice_stats> for slice-by-slice Dice scores.

  • “jaccard” : global Jaccard index.

  • “jaccard_flat”: Jaccard index of ROIs flattened in the orientation specified in <view>.

  • “jaccard_slice”: Jaccard index on a single slice.

  • “jaccard_slice_stats”: statistics specified in <slice_stats> for slice-by-slice Jaccard indices.

  • “centroid”: 3D centroid distance vector.

  • “abs_centroid”: magnitude of 3D centroid distance vector.

  • “abs_centroid_flat”: magnitude of 3D centroid distance vector projected into the plane specified in <view>.

  • “centroid_slice”: 2D centroid distance vector on a single slice.

  • “centroid_slice_stats”: statistics specified in <slice_stats> for slice-by-slice 2D centroid distance vectors.

  • “abs_centroid_slice”: magnitude of 2D centroid distance vector on a single slice.

  • “abs_centroid_slice_stats”: statistics specified in <slice_stats> for slice-by-slice magnitudes of 2D centroid distance vectors.

  • “added_path_length”: path length added to contours (own path - other path).

  • “added_path_length_flat”: path length added to contours (own path - other path) after projection into the plane specified in <view>.

  • “added_path_length_slice”: path length added to contours (own path - other path) in a single slice.

  • “added_path_length_slice_stats”: statistics specified in <slice_stats> for slice-by-slice path length added to contours (own path - other path).

  • “volume_diff”: volume difference (own volume - other volume).

  • “rel_volume_diff”: volume difference divided by own volume.

  • “volume_ratio”: volume ratio (own volume / other volume).

  • “area_diff”: area difference (own area - other area) on a single slice.

  • “rel_area_diff”: area difference divided by own area on a single slice.

  • “area_ratio”: area ratio (own area / other area).

  • “area_diff_flat”: area difference of ROIs flattened in the orientation specified in <view>.

  • “area_diff_slice_stats”: statistics specified in <slice_stats> for slice-by-slice area differences.

  • “rel_area_diff_flat”: relative area difference of ROIs flattened in the orientation specified in <view>.

  • “rel_area_diff_slice_stats”: statistics specified in <slice_stats> for relative area differences of ROIs.

  • “area_ratio_flat”: area ratio of ROIs flattened in the orientation specified in <view>.

  • “area_ratio_slice_stats”: statistics specified in <slice_stats> for slice-by-slice area ratios.

  • “mean_signed_surface_distance”: mean signed surface distance.

  • “mean_signed_surface_distance_flat”: mean signed surface distance of ROIs flattened in the orientation specified in <view>.

  • “mean_surface_distance”: mean surface distance.

  • “mean_surface_distance_flat”: mean surface distance of ROIs flattened in the orientation specified in <view>.

  • “rms_surface_distance”: RMS surface distance.

  • “rms_surface_distance_flat”: RMS surface distance of ROIs flattened in the orientation specified in <view>.

  • “rms_signed_surface_distance”: RMS signed surface distance.

  • “rms_signed_surface_distance_flat”: RMS signed surface distance of ROIs flattened in the orientation specified in <view>.

  • “hausdorff_distance”: Hausdorff distance.

  • “hausdorff_distance_flat”: Hausdorff distance of ROIs flattened in the orientation specified in <view>.

  • “mean_under_contouring”: Sum of absolute values of negative distances to conformity, divided by volume in union of ROIs compared.

  • “mean_under_contouring_flat”: Sum of absolute values of negative distances to conformity, divided by volume, flattened in the orientation specified in <view>. in union of ROIs compared.

  • “mean_over_contouring”: Sum of positive distances to conformity, divided by volume in union of ROIs compared.

  • “mean_over_contouring_flat”: Sum of positive distances to conformity, divided by volume in union of ROIs compared, flattened in the orientation specified in <view>.

  • “mean_distance_to_conformity”: Sum of mean_under_contouring and mean_over_contouring.

  • “mean_distance_to_conformity_flat”: Sum of mean_under_contouring_flat and mean_over_contouring_flat.

If None, defaults to [“dice”, “centroid”].

vol_unitsstr, default=”mm”

Units to use for volume. Can be “mm” (=mm^3), “ml”, or “voxels”.

area_unitsstr, default=”mm”

Units to use for areas. Can be “mm” (=mm^2) or “voxels”.

centroid_units:

Units to use for centroids. Can be “mm” or “voxels”.

viewstr, default=”x-y”

Orientation in which to compute metrics. Only relevant for single-slice metrics or flattened metrics.

slint, default=None

Slice number on which to compute metrics. Only relevant for single-slice metrics (area, centroid_slice, length_slice). If <sl>, <idx>, and <pos> are all None, the central slice of the ROI will be used.

idxint, default=None

Slice index array on which to compute metrics. Only relevant for single-slice metrics (area, centroid_slice, length_slice). Used if <sl> is None.

posfloat, default=None

Slice position in mm on which to compute metrics. Only relevant for single-slice metrics (area, centroid_slice, length_slice). Used if <sl> and <idx> are both None.

methodstr, default=None

Method to use for metric calculation. Can be either “contour” (use shapely polygons) or “mask” (use binary mask). If None, the value set in self.default_geom_method will be used. Note that flattened metrics and surface distance metrics enforce use of the “mask” method.

slice_statsstr/list/dict, default=None

Specification of statistics to be calculated relative to slice-by-slice metric values. Used for all metrics with suffix “_slice_stats” in the <metrics> list.

A statistic is specified by the name of the function for its calculation in the Python statistics module:

https://docs.python.org/3/library/statistics.html

For its use here, the relevant function must require a single-variable input, must not require any keyword arguments, and must return a single number.

Available options include: “mean”, “median”, “mode”, “stdev”.

Statistics to be calculated can be specified using any of the following:

  • String specifying single statistic to be calculated, with slices considered as given by default_by_slice, for example: “mean”;

  • List specifying multiple statistics to be calculated, with slices considered as given by default_by_slice, for example: [“mean”, “stdev”];

  • Dictionary where keys specify slices to be considered, and values specify statistics (string or list), for example: {“union”: [“mean”, “stdev”]}. Valid slice specifications are as listed for default_by_slice.

default_by_slice: str, default=None

Default specification of slices to be considered when calculating slice-by-slice statistics. The valid specifications are:

  • “left”: consider only slices containing self;

  • “right”: consider only slices containing other roi;

  • “union”: consider slices containing either of self and other roi;

  • “intersection”: consider slices containing both of self and other roi.

If None, use skrt.core.Defaults().by_slice

units_in_headerbool, default=False

If True, units will be included in column headers.

global_vs_slice_headerbool, default=False

If True, the returned DataFrame will have an extra set of headers splitting the table into “global” and “slice” metrics.

name_as_indexbool, default=True

If True, the index column of the pandas DataFrame will contain the ROI’s names; otherwise, the name will appear in a column named “ROI”.

nice_columnsbool, default=False

If False, column names will be the same as the input metrics 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.

forcebool, default=True

If False, global metrics for each ROI (volume, 3D centroid, 3D lengths) will only be calculated if they have not been calculated before; if True, all metrics will be recalculated.

voxel_sizetuple, default=(1, 1, 1)

Voxel size (dx, dy, dz) in mm to be used for ROI masks from which to calculate surface distances. If None, the mask voxel size of <other> is used. If an individual element is None, the value of the corresponding element for the mask voxel size of <other> is used. A value other than None forces creation of masks that just cover the volume occupied by the two ROIs being compared, potentially reducing the time for surface-distance calculations.

match_lengthsbool/str/list, default=False

If set to True, to the name of the other ROI, or to a list of names including the name of the other ROI, match ROI lengths (z-dimensions) before comparison. The strategy used is defined by the value of match_lengths_strategy.

match_lengths_strategyint, default=1

Strategy to use for matching ROI lengths (z-dimensions):

  • 0 : Crop this ROI to the z-extents of the other ROI;

  • 1 : Crop the other ROI to the z-exents of this ROI;

  • 2Crop this ROI to the z-extents of the other ROI, then

    crop the other ROI to the cropped z-extents of this ROI.

For a value other than 0, 1, 2, no length matching is performed.

get_comparison_name(roi, camelcase=False, colored=False, grey=False, roi_kwargs={})

Get name of comparison between this ROI and another.

get_contours(view='x-y', idx_as_key=False, most_points=False)

Get dict of contours in a given orientation.

Parameters:

viewstr, default=”x-y”

View in which to obtain contours.

idx_as_keybool, default=False

If True, use slice indices as dictionary keys; if False, use slice z-coordinates as dictionary keys.

most_pointsbool, default=False

If True, return only the contour with most points for each slice; if False, return all contours for each slice.

get_contours_on_slice(view='x-y', sl=None, idx=None, pos=None)
get_crop_limits(crop_margins=None, method=None)

Get crop limits corresponding to ROI extents plus margins.

The tuples of limits returned, in the order (x, y, z) can be used, for example, as inputs to skrt.image.Image.crop().

This method is similar to the method get_extents(), but allows different margins on each side of the ROI.

Parameters:

crop_marginsfloat/tuple, default=None

Float or three-element tuple specifying the margins, in mm, to be added to ROI extents. 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).

methodstr, default=None

Method to use for extent calculation. 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.

get_dice(other, single_slice=False, view='x-y', sl=None, idx=None, pos=None, method=None, flatten=False, by_slice=None, value_for_none=None, slice_stat=None, slice_stat_kwargs=None)

Get Dice score with respect to another ROI, globally, on a single slice, slice by slice, or slice averaged.

Parameters:

otherROI

Other ROI to compare with this ROI.

single_slicebool, default=False

If False, the global 3D Dice score of the full ROIs will be returned; otherwise, the 2D Dice score on a single slice will be returned.

viewstr, default=”x-y”

Orientation of slice on which to get Dice score. Only used if single_slice=True. If using, <ax> must be an axis that lies along the slice in this orientation.

slint, default=None

Slice number. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of this ROI will be used.

idxint, default=None

Array index of slice. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of this ROI will be used.

posfloat, default=None

Slice position in mm. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of this ROI will be used.

methodstr, default=None
Method to use for Dice score calculation. Can be:
  • “contour”: get intersections and areas of shapely contours.

  • “mask”: count intersecting voxels in binary masks.

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

flattenbool, default=False

If True, all slices will be flattened in the given orientation and the Dice score of the flattened slices will be returned. Only available if method=”mask”.

by_slicestr, default=None

If one of “left”, “right”, “union”, “intersection”, calculate Dice scores slice by slice for each slice containing self and/or other:

  • “left”: consider only slices containing self;

  • “right”: consider only slices containing other;

  • “union”: consider slices containing either of self and other;

  • “intersection”: consider slices containing both of self and other.

If slice_stat is None, return a dictionary where keys are slice positions and values are the calculated Dice scores. Otherwise, return for the calculated Dice scores the statistic specified by slice_stat.

value_for_nonefloat, default=None

For single_slice and by_slice, value to be returned for slices where Dice score is undetermined (None). For slice_stat, value to substitute for any None values among the inputs for calculating slice-based statistic. If None in the latter case, None values among the inputs are omitted.

slice_statstr, default=None

Single-variable statistic(s) to be returned for slice-by-slice Dice scores. This should be the name of the function for calculation of the statistic(s) in the Python statistics module:

https://docs.python.org/3/library/statistics.html

Available options include: “mean”, “median”, “mode”, “stdev”, “quantiles”. Disregarded if None.

If by_slice is None and slice_stat is different from None, skrt.core.Defaults().by_slice is used for the former.

slice_stat_kwargsdict, default=None

Keyword arguments to be passed to function of statistics module for calculation relative to slice values. For example, if quantiles are required for 10 intervals, rather than for the default of 4, this can be specified using:

slice_stat_kwargs{“n” : 10}

For available keyword options, see documentation of statistics module at:

https://docs.python.org/3/library/statistics.html

get_dicom_dataset()

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

get_dummy_image(**kwargs)

Make a dummy image that covers the area spanned by this ROI. Returns an Image object.

Parameters:

voxel_sizelist, default=None

Voxel size in mm in the dummy image in the x-y plane, given as [vx, vy]. If <shape> and <voxel_size> are both None, voxel sizes of [1, 1] will be used by default. The voxel size in the z direction is defined by <slice_thickness>.

shapelist, default=None

Number of voxels in the dummy image in the x-y plane, given as [nx, ny]. Only used if <voxel_size> is None. The number of voxels in the z direction will be taken from the number of slices in the x-y contours dictionary.

fill_valint/float, default=1e4

Value with which the voxels in the dummy image should be filled.

bufferint, default=1

Number of empty buffer voxels to add outside the ROI in each direction.

slice_thicknessfloat, default=None

Voxel size in mm in the dummy image in the z direction. If None, the value used is the minimum distance between slice positions in the x-y contours dictionary.

get_enclosing_roi(oriented=False)

Get ROI defined, slice by slice, by the minimum rectangle that encloses this ROI.

Parameter:

  • oriented: bool, default=False If True, rectangles at all orientations are considered when selecting the rectangle of minimum area. If False, only rectangles with sides parallel to the x and y axes are considered.

get_extent(ax='z', single_slice=False, view='x-y', sl=None, idx=None, pos=None, method=None, origin=None)

Get minimum and maximum extent of the ROI in mm along a given axis.

axstr/int, default=”z”

Axis along which to return extent. Should be one of [“x”, “y”, “z”] or [0, 1, 2]

single_slicebool, default=False

If False, the 3D extent of the entire ROI will be returned; otherwise, the 2D extent of a single slice will be returned.

viewstr, default=”x-y”

Orientation of slice on which to get extent. Only used if single_slice=True. If using, <ax> must be an axis that lies along the slice in this orientation.

slint, default=None

Slice number. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of the ROI will be used.

idxint, default=None

Array index of slice. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of the ROI will be used.

posfloat, default=None

Slice position in mm. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of the ROI will be used.

methodstr, default=None

Method to use for extent calculation. 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.

originint/float/tuple, default=None

Point with respect to which extents are to be determined. This can be an integer or float specifying the point’s coordinate along axis <ax>; or it can be a tuple specifying the point’s (x, y, z) coordinates, where only the coordinate along axis <ax> will be considered. If None, the origin coordinate is taken to be 0.

get_extent_diff(other, ax='z', single_slice=False, view='x-y', sl=None, idx=None, pos=None, method=None, by_slice=None, value_for_none=None, slice_stat=None, slice_stat_kwargs=None)

Get differences between minimum and maximum extent in mm, along a given axis, of this ROI and other ROI.

axstr/int, default=”z”

Axis along which to return differences in extent. Should be one of [“x”, “y”, “z”] or [0, 1, 2]

single_slicebool, default=False

If False, the 3D differences in extent of the entire ROI will be returned; otherwise, the 2D differences in extent of a single slice will be returned.

viewstr, default=”x-y”

Orientation of slice on which to get differences in extent. Only used if single_slice=True. If using, <ax> must be an axis that lies along the slice in this orientation.

slint, default=None

Slice number. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of the ROI will be used.

idxint, default=None

Array index of slice. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of the ROI will be used.

posfloat, default=None

Slice position in mm. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of the ROI will be used.

methodstr, default=None

Method to use for extent calculations. 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.

by_slicestr, default=None

If one of “left”, “right”, “union”, “intersection”, calculate Dice scores slice by slice for each slice containing self and/or other:

  • “left”: consider only slices containing self;

  • “right”: consider only slices containing other;

  • “union”: consider slices containing either of self and other;

  • “intersection”: consider slices containing both of self and other.

If slice_stat is None, return a dictionary where keys are slice positions and values are the calculated Dice scores. Otherwise, return for the calculated Dice scores the statistic specified by slice_stat.

value_for_nonefloat, default=None

For single_slice and by_slice, value to be returned for slices where Dice score is undetermined (None). For slice_stat, value to substitute for any None values among the inputs for calculating slice-based statistic. If None in the latter case, None values among the inputs are omitted.

slice_statstr, default=None

Single-variable statistic(s) to be returned for slice-by-slice Dice scores. This should be the name of the function for calculation of the statistic(s) in the Python statistics module:

https://docs.python.org/3/library/statistics.html

Available options include: “mean”, “median”, “mode”, “stdev”, “quantiles”. Disregarded if None.

If by_slice is None and slice_stat is different from None, skrt.core.Defaults().by_slice is used for the former.

slice_stat_kwargsdict, default=None

Keyword arguments to be passed to function of statistics module for calculation relative to slice values. For example, if quantiles are required for 10 intervals, rather than for the default of 4, this can be specified using:

slice_stat_kwargs{“n” : 10}

For available keyword options, see documentation of statistics module at:

https://docs.python.org/3/library/statistics.html

get_extents(buffer=None, buffer_units='mm', method=None, origin=None)

Get minimum and maximum extent of the ROI in mm along all three axes, returned in order [x, y, z]. Optionally apply a buffer to the extents such that they cover more than the ROI’s area.

Parameters:

bufferfloat, default=None

Optional buffer to add to the extents. Units set by buffer_units.

buffer_unitsstr, default=”mm”

Units for buffer, if using. Can be “mm”, “voxels”, or “frac” (which applies buffer as a fraction of total length in each dimension).

methodstr, default=None

Method to use for extent calculation. 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.

origintuple, default=None

Tuple specifying the (x, y, z) coordinates of the point with respect to which extents are to be determined. If None, then (0, 0, 0) is used.

get_geometry(metrics=None, vol_units='mm', area_units='mm', length_units='mm', centroid_units='mm', view='x-y', sl=None, pos=None, idx=None, method=None, units_in_header=False, global_vs_slice_header=False, name_as_index=True, nice_columns=False, decimal_places=None, force=True, html=False)

Return a pandas DataFrame or html table of the geometric properties listed in <metrics>.

Parameters:

metricslist, default=None

List of metrics to include in the table. Options:

  • “volume” : volume of entire ROI.

  • “area”: area of ROI on a single slice.

  • “centroid”: 3D centre-of-mass of ROI; will be split into three columns corresponding to the three axes.

  • “centroid_slice”: 2D centre of mass on a single slice. Will be split into two columns corresponding to the two axes on the slice.

  • “length”: lengths of the ROI in each direction; will be split into three columns corresponding to the three axes.

  • “length_slice”: length of the ROI on a single slice; will be split into two columns corresponding to the two axes on the slice.

If None, defaults to [“volume”, “centroid”]

vol_unitsstr, default=”mm”

Units to use for volume. Can be “mm” (=mm^3), “ml”, or “voxels”.

area_unitsstr, default=”mm”

Units to use for areas. Can be “mm” (=mm^2) or “voxels”.

length_unitsstr, default=”mm”:

Units to use for lengths. Can be “mm” or “voxels”.

centroid_units:

Units to use for centroids. Can be “mm” or “voxels”.

viewstr, default=”x-y”

Orientation in which to compute metrics. Only relevant for single-slice metrics (area, centroid_slice, length_slice).

slint, default=None

Slice number on which to compute metrics. Only relevant for single-slice metrics (area, centroid_slice, length_slice). If <sl>, <idx>, and <pos> are all None, the central slice of the ROI will be used.

idxint, default=None

Slice index array on which to compute metrics. Only relevant for single-slice metrics (area, centroid_slice, length_slice). Used if <sl> is None.

posfloat, default=None

Slice position in mm on which to compute metrics. Only relevant for single-slice metrics (area, centroid_slice, length_slice). Used if <sl> and <idx> are both None.

methodstr, default=None

Method to use for metric calculation. Can be either “contour” (use shapely polygons) or “mask” (use binary mask). If None, the value set in self.default_geom_method will be used.

units_in_headerbool, default=False

If True, units will be included in column headers.

global_vs_slice_headerbool, default=False

If True, the returned DataFrame will have an extra set of headers splitting the table into “global” and “slice” metrics.

name_as_indexbool, default=True

If True, the index column of the pandas DataFrame will contain the ROI’s name; otherwise, the name will appear in a column named “ROI”.

nice_columnsbool, default=False

If False, column names will be the same as the input metrics 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.

forcebool, default=True

If False, global metrics (volume, 3D centroid, 3D lengths) will only be calculated if they have not been calculated before; if True, all metrics will be recalculated.

get_hausdorff_distance(other, **kwargs)
get_idx(view, sl=None, idx=None, pos=None)

Get an array index from either a slice number, index, or position.

get_image()

Return Image object associated with this ROI.

get_indices(view='x-y', method=None)

Get list of slice indices on which this ROI exists.

get_intensities(image=None, standardise=True)

Return 1D numpy array containing all of the intensity values for the voxels inside self.

Parameters:

imageskrt.image.Image, default=None

Image object for which 1D array of intensity values is to be obtained. If None, the image associated with the ROI is used.

standardisebool, default=False

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

get_intensities_3d(image=None, standardise=True)

Return copy of an image array that has values retained inside self, and is set to zero elsewhere.

Parameter:

imageskrt.image.Image, default=None

Image object for which 3D array with intensity values retained inside ROI, and NaN elsewhere, is to be obtained. If None, the image associated with the ROI is used.

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_intersection_union_size(other, single_slice=False, view='x-y', sl=None, idx=None, pos=None, method=None, flatten=False)

Get intersection, union and mean size with respect to another ROI. Values are returned as volumes for the full ROIs, or as areas for a single slice.

Parameters:

otherROI

Other ROI to compare with this ROI.

single_slicebool, default=False

If False, the volumes of intersection and union of the full ROIs, and the mean ROI volume will be returned; otherwise, the areas of intersection and union on a single slice, and the mean ROI area, will be returned.

viewstr, default=”x-y”

Orientation of slice on which to get areas of intersection and union, and mean ROI area. Only used if single_slice=True.

slint, default=None

Slice number. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of this ROI will be used.

idxint, default=None

Array index of slice. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of this ROI will be used.

posfloat, default=None

Slice position in mm. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of this ROI will be used.

methodstr, default=None

Method to use for calculating intersection, union, and mean size. Can be:

  • “contour”: get intersections and areas of shapely contours.

  • “mask”: count intersecting voxels in binary masks.

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

flattenbool, default=False

If True, all slices will be flattened in the given orientation and the areas of intersection and union, and the mean ROI area, will be returned for the flattened slices. Only available if method=”mask”.

get_jaccard(other, single_slice=False, view='x-y', sl=None, idx=None, pos=None, method=None, flatten=False, by_slice=None, value_for_none=None, slice_stat=None, slice_stat_kwargs=None)

Get Jaccard index with respect to another ROI.

The Jaccard index may be obtained either globally or on a single slice.

Parameters:

otherROI

Other ROI to compare with this ROI.

single_slicebool, default=False

If False, the global 3D Jaccard index of the full ROIs will be returned; otherwise, the 2D Jaccard index on a single slice will be returned.

viewstr, default=”x-y”

Orientation of slice on which to get Jaccard index. Only used if single_slice=True. If using, <ax> must be an axis that lies along the slice in this orientation.

slint, default=None

Slice number. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of this ROI will be used.

idxint, default=None

Array index of slice. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of this ROI will be used.

posfloat, default=None

Slice position in mm. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of this ROI will be used.

methodstr, default=None
Method to use for Dice score calculation. Can be:
  • “contour”: get intersections and areas of shapely contours.

  • “mask”: count intersecting voxels in binary masks.

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

flattenbool, default=False

If True, all slices will be flattened in the given orientation and the Dice score of the flattened slices will be returned. Only available if method=”mask”.

by_slicestr, default=None

If one of “left”, “right”, “union”, “intersection”, calculate Dice scores slice by slice for each slice containing self and/or other:

  • “left”: consider only slices containing self;

  • “right”: consider only slices containing other;

  • “union”: consider slices containing either of self and other;

  • “intersection”: consider slices containing both of self and other.

If slice_stat is None, return a dictionary where keys are slice positions and values are the calculated Jaccard indices. Otherwise, return for the calculated Jaccard indices the statistic specified by slice_stat.

value_for_nonefloat, default=None

For single_slice and by_slice, value to be returned for slices where Jaccard index is undetermined (None). For slice_stat, value to substitute for any None values among the inputs for calculating slice-based statistic. If None in the latter case, None values among the inputs are omitted.

slice_statstr, default=None

Single-variable statistic(s) to be returned for slice-by-slice Jaccard indices. This should be the name of the function for calculation of the statistic(s) in the Python statistics module:

https://docs.python.org/3/library/statistics.html

Available options include: “mean”, “median”, “mode”, “stdev”, “quantiles”. Disregarded if None.

If by_slice is None and slice_stat is different from None, the former defaults to “union”.

slice_stat_kwargsdict, default=None

Keyword arguments to be passed to function of statistics module for calculation relative to slice values. For example, if quantiles are required for 10 intervals, rather than for the default of 4, this can be specified using:

slice_stat_kwargs{“n” : 10}

For available keyword options, see documentation of statistics module at:

https://docs.python.org/3/library/statistics.html

get_length(ax='z', single_slice=False, view='x-y', sl=None, idx=None, pos=None, units='mm', method=None, force=True)

Get ROI length along a given axis. If single_slice=False (i.e. a global length is requested), calculated length will be cached in self._length[ax][units] and returned if called again, unless force=True.

Parameters:

axstr/int, default=”z”

Axis along which to return length; should be one of [“x”, “y”, “z”] or [0, 1, 2].

single_slicebool, default=False

If False, the length of the entire ROI will be returned; otherwise, the length on a single slice will be returned.

viewstr, default=”x-y”

Orientation of slice on which to get length. Only used if single_slice=True. If using, <ax> must be an axis that lies along the slice in this orientation.

slint, default=None

Slice number. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of the ROI will be used.

idxint, default=None

Array index of slice. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of the ROI will be used.

posfloat, default=None

Slice position in mm. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of the ROI will be used.

unitsstr, default=”mm”
Units of length. Can be either of:
  • “mm”: return length in millimetres.

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

If units=”voxels” is requested but this ROI only has contours and no voxel size information, an error will be raised (unless ax=”z”, in which case voxel size will be inferred from spacing between slices).

methodstr, default=None
Method to use for length calculation. Can be:
  • “contour”: get length from min/max positions of contour(s).

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

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

forcebool, default=True

If True, the length will always be recalculated; otherwise, it will only be calculated if it has not yet been cached in self._volume. Note that if single_slice=True, the length will always be recalculated.

get_mask(view='x-y', flatten=False, standardise=False, force_standardise=False)

Get binary mask, optionally flattened in a given orientation.

get_mask_image()

Get image object representing ROI mask.

get_mask_to_contour_volume_ratio()

Get ratio to ROI “mask” volume to ROI “contour” volume.

In principle, volume estimates from “mask” and “contour” methods should be similar. The two estimates may be different if, for example, the image from which a mask is created doesn’t fully cover the contour extents.

get_mean_distance_to_conformity(other, vol_units='mm', **kwargs)

Obtain mean distance to conformity for <other> relative to <self>.

The mean distance to conformity is as defined in: https://doi.org/10.1259/bjr/27674581 Technically the mean distance to conformity isn’t a distance, but is a distance divided by a volume.

This function returns a skrt.core.Data object, with the following information:

n_voxel : number of voxels in the union of the ROIs considered.

voxel_size : voxel size (dx, dy, dz) in millimetres, in the ROI masks used in distance calculations.

mean_under_contouring : sum of absolute values of negative distances to conformity, divided by volume in union of ROIs considered.

mean_over_contouring : sum of positive distances to conformity, divided by volume in union of ROIs considered.

mean_distance_to_conformity : sum of mean_under_contouring and mean_over_contouring.

Parameters: vol_units : str, default=”mm”

Units to use for volume in denominator when calculating mean_under_contouring and mean_overcontouring. Can be “mm” (=mm^3), “ml”, or “voxels”.

kwargs

Keyword arguments are passed to skrt.structures.ROI.get_surface_distances(). See documentation of this method for parameter details.

get_mean_surface_distance(other, **kwargs)

Obtain mean distance between surface of <other> and surface of <self>.

For parameters that may be passed, see documentation for: skrt.ROI.get_surface_distances().

get_metric_by_slice(other, metric=None, by_slice=None, view='x-y', method=None)

Get dictionary of slice-by-slice values for comparison metric.

Each key of the returned dictionary is a slice position (mm), and the associated value is the metric value for the slice.

Parameters:

otherROI

Other ROI to compare with this ROI.

metricstr, default=None

Metric to be evaluated.

by_slice: str, default=None

Slices to be considered. The valid specifications are:

  • “left”: consider only slices containing self;

  • “right”: consider only slices containing other roi;

  • “union”: consider slices containing either of self and other roi;

  • “intersection”: consider slices containing both of self and other roi.

If None, use skrt.core.Defaults().by_slice

viewstr, default=”x-y”

Orientation of slices on which to get metric values.

methodstr, default=None
Method to use for metric calculation. Can be:
  • “contour”: calculate metric from shapely contours.

  • “mask”: calcualte metric from binary masks.

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

get_mid_idx(view='x-y', **kwargs)

Get central slice index of this ROI in a given orientation.

get_name(original=False)

Load self and get name. If <original> is True, get the original name.

get_np_voxel_size(view=None)

Get voxel_size for numpy axis ordering and specified view.

viewstr

Orientation considered for 2D image or projection. Can be “x-y”, “x-z”, “y-x”, “y-z”, “z-x”, or “z-y”.

get_nz_contours()

Get number of voxels in the z direction using positions of contours.

get_origin()

Load self and get origin.

get_patch(plot_type=None, color=None, opacity=None, linewidth=None, name=None)

Obtain patch reflecting ROI characteristics for plotting.

The patch obtained can be used as a handle in legend creation.

Parameters:

plot_typestr, default=None

Plotting type. If None, will be either “contour” or “mask” depending on the input type of the ROI. Options:

  • “contour”

  • “mask”

  • “centroid” (contour with marker at centroid)

  • “filled” (transparent mask + contour)

  • “filled centroid” (filled with marker at centroid)

colormatplotlib color, default=None

Color with which to plot the ROI; overrides the ROI’s own color. If None, self.color will be used.

opacityfloat, default=None

Opacity to use if plotting mask (i.e. plot types “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.

linewidthfloat, default=None

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

namestr, default=None

Name identifying ROI. If None, self.name will be used.

get_plans()

Return list of Plan objects associated with this ROI.

get_polygons(view='x-y', idx_as_key=False)

Get dict of polygons for each slice.

get_polygons_on_slice(view='x-y', sl=None, idx=None, pos=None)

Get shapely polygon objects corresponding to a given slice.

get_relative_area_diff(other, view='x-y', sl=None, idx=None, pos=None, units='mm', method=None, flatten=False, by_slice=None, slice_stat=None, value_for_none=None, **slice_stat_kwargs)

Get relative area of another ROI with respect to own area.

get_relative_volume_diff(other, **kwargs)

Get relative volume of another ROI with respect to own volume.

get_rms_surface_distance(other, **kwargs)
get_roi_slice(z_fraction=1, suffix=None)

Get ROI object corresponding to x-y slice through this ROI.

Parameter:

z_fractionfloat, default=1

Position along z axis at which to take slice through ROI. The position is specified as the fractional 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.

suffixstr, default=None

Suffix to append to own name, to form name of output ROI. If None, append z_fraction, with value given to two decimal places.

get_slice(*args, force_standardise=False, **kwargs)
get_slice_positions(other=None, view='x-y', position_as_idx=False, method='union')

Get ordered list of slice positions for self and other.

Parameters:

otherskrt.structures.ROI, default=None

Second ROI of a pair for which slice positions are be obtained. Disregarded if None.

viewstr, default=”x-y”

View in which to obtain slices.

position_as_idxbool, default=False

If True, return positions as slice indices; if False, return positions as slice z-coordinates (mm).

method: str, default=”union”

String specifying slices for which positions are to be obtained, for ROIs self and other.

  • “left” (or other is None): return positions of slices containing self;

  • “right”: return positions of slices containing other;

  • “union”: return positions of slices containing either self or other;

  • “intersection”: return positions of slices containing both self and other.

get_slice_stat(other, metric=None, slice_stat=None, by_slice=None, value_for_none=None, view='x-y', method=None, **slice_stat_kwargs)

Get statistic for slice-by-slice comparison metric.

Parameters:

otherROI

Other ROI to compare with this ROI.

metricstr, default=None

Metric for which statistic for slice-by-slice values is to be returned.

slice_statstr, default=None

Single-variable statistic(s) to be returned for slice-by-slice Dice scores. This should be the name of the function for calculation of the statistic(s) in the Python statistics module:

https://docs.python.org/3/library/statistics.html

Available options include: “mean”, “median”, “mode”, “stdev”, “quantiles”.

by_slice: str, default=None

Slices to be considered. The valid specifications are:

  • “left”: consider only slices containing self;

  • “right”: consider only slices containing other roi;

  • “union”: consider slices containing either of self and other roi;

  • “intersection”: consider slices containing both of self and other roi.

If None, use skrt.core.Defaults().by_slice

value_for_nonefloat, default=None

Value to substitute for any None values among slice metric values. If None, None values among the metric values are omitted.

viewstr, default=”x-y”

Orientation of slices on which to get metric values.

methodstr, default=None
Method to use for metric calculation. Can be:
  • “contour”: calculate metric from shapely contours.

  • “mask”: calcualte metric from binary masks.

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

slice_stat_kwargsdict, default=None

Keyword arguments to be passed to function of statistics module for calculation relative to slice values. For example, if quantiles are required for 10 intervals, rather than for the default of 4, this can be specified using:

slice_stat_kwargs{“n” : 10}

For available keyword options, see documentation of statistics module at:

https://docs.python.org/3/library/statistics.html

get_slice_stats(other, metrics=None, slice_stats=None, default_by_slice=None, method=None, view='x-y', separate_components=False)

Get dictionary of statistics for slice-by-slice comparison metrics.

Parameters:

otherROI

Other ROI to compare with this ROI.

metricsstr/list, default=None

Metric(s) for which statistic(s) for slice-by-slice calculations are to be returned. A single metric can by speficied as a string. Multiple metrics can be specified as a list of strings.

slice_statsstr/list/dict, default=None

Specification of statistics to be calculated relative to slice-by-slice metric values. Used for all metrics with suffix “_slice_stats” in the <metrics> list.

A statistic is specified by the name of the function for its calculation in the Python statistics module:

https://docs.python.org/3/library/statistics.html

For its use here, the relevant function must require a single-variable input, must not require any keyword arguments, and must return a single number.

Available options include: “mean”, “median”, “mode”, “stdev”.

Statistics to be calculated can be specified using any of the following:

  • String specifying single statistic to be calculated, with slices considered as given by default_by_slice, for example: “mean”;

  • List specifying multiple statistics to be calculated, with slices considered as given by default_by_slice, for example: [“mean”, “stdev”];

  • Dictionary where keys specify slices to be considered, and values specify statistics (string or list), for example: {“union”: [“mean”, “stdev”]}. Valid slice specifications are as listed for default_by_slice.

default_by_slice: str, default=None

Default specification of slices to be considered when calculating slice-by-slice statistics. The valid specifications are:

  • “left”: consider only slices containing self;

  • “right”: consider only slices containing other roi;

  • “union”: consider slices containing either of self and other roi;

  • “intersection”: consider slices containing both of self and other roi.

If None, use skrt.core.Defaults().by_slice

viewstr, default=”x-y”

Orientation of slices on which to get metric values.

methodstr, default=None
Method to use for metric calculation. Can be:
  • “contour”: calculate metric from shapely contours.

  • “mask”: calculate metric from binary masks.

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

separate_components: bool, default=False

If False, return a metric represented by a vector as a list of component values. If true, return a separate metric for each component, labelling by the component axes determined from <view>.

get_slice_thickness_contours()

Get z voxel size using positions of contours.

get_surface_area(method=None, force=True)

Get ROI surface area (mm^2). The calculated surface area will be cached in self._surface_area and returned if called again, unless force=True.

Voxelisation affects the accuracy of the calculations. In tests using synthetic data for cubes of side length 40 mm and spheres of diameter 40 mm, initialised from masks with a voxel size of 1 mm x 1 mm x 1mm, the calculated surface area was underestimated by 2% for the cubes, and was overestimated by 10% for the spheres, with little difference between “contour” and “mask” methods.

Parameters:

methodstr, default=None
Method to use for calculation of surface area. Can be:
  • “contour”: compute surface area by considering the ROI as being made of polygonal wedges, summing the areas of the wedge sides and the non-overlapping parts of adjacent wedges.

  • “mask”: compute area of the surface formed by meshing the ROI mask using the marching-cubes algorithm.

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

Note that if self.get_surface_area has already been called with one method, the same cached result will be returned if calling with a different method unless force=True.

forcebool, default=True

If True, the surface area will always be recalculated; otherwise, it will only be calculated if it has not yet been cached in self._surface_area.

get_surface_distance_metrics(other, **kwargs)

Get the mean surface distance, RMS surface distance, and Hausdorff distance.

get_surface_distances(other, single_slice=False, signed=False, view='x-y', sl=None, idx=None, pos=None, connectivity=2, flatten=False, symmetric=None, conformity=False, in_slice=True, voxel_size=None, voxel_dim_tolerance=0.1, by_slice=None)

Get vector of surface distances between two ROIs.

Surface distances may be signed or unsigned, and may be for a single slice through the ROIs, or for the 3D volumes.

This function uses ideas outlined at: https://mlnotebook.github.io/post/surface-distance-function/

Parameters:

single_slicebool, default=False

If False, return surface distances relative to 3D volumes. Otherwise, return surface distances for a single image slice.

signedbool, default=False

If False, return absolute surface distances. If True, return signed surface distances. A point on the surface of <other> is taken to be at a positive distance if outside <self>, and at a negative distance if inside.

viewstr, default=”x-y”

Orientation of slice for which to obtain surface distances. Only used if either <single_slice> or <flatten> is True.

slint, default=None

Slice number. If none of <sl>, <idx> or <pos> is supplied but <single_slice> is True, the central slice of the ROI will be used.

idxint, default=None

Array index of slice. If none of <sl>, <idx> or <pos> is supplied but <single_slice> is True, the central slice of the ROI will be used.

posfloat, default=None

Slice position in mm. If none of <sl>, <idx> or <pos> is supplied but <single_slice> is True, the central slice of the ROI will be used.

connectivity: int, default=2

Integer defining which voxels to consider as neighbours when performing erosion operation to identify ROI surfaces. This is passed as <connectivity> parameter to: scipy.ndimage.generate_binary_structure For further details, see: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.generate_binary_structure.html

flattenbool, default=False

If True, all slices for each ROI will be flattened in the given orientation, and surface distances relative to the flattened slice will be returned.

symmetricbool, default=None

If True, the distances returned are from the surface of <other> to the surface of <self> and from the surface of <self> to the surface of <other>. If False, distances are from the surface of <other> to the surface of <self> only. If None, set to the opposiste of <signed>.

conformitybool, default=False

If True, distances returned are signed distances to conformity, as defined in: https://doi.org/10.1259/bjr/27674581 In this case, the values of <signed> and <symmetric> are disregarded.

in_slicebool, default=True

If True, only intra-slice connectivity is considered when performing erosion to identify ROI surfaces.

voxel_sizetuple, default=None

Voxel size (dx, dy, dz) in mm to be used for ROI masks from which to calculate surface distances. If None, the mask voxel size of <other> is used. If an individual element is None, the value of the corresponding element for the mask voxel size of <other> is used.

voxel_dim_tolerancefloat, default=0.1

Tolerence used when determining whether <voxel_size> is different from the voxel size of the images associated with each ROI.

by_slicestr, default=None

If one of “left”, “right”, “union”, “intersection”, calculate surface distances scores slice by slice for each slice containing self and/or other:

  • “left”: consider only slices containing self;

  • “right”: consider only slices containing other;

  • “union”: consider slices containing either of self and other;

  • “intersection”: consider slices containing both of self and other.

Return a dictionary where keys are slice positions and values are lists of calculated surface distances.

get_translation_to_align(other, z_fraction1=None, z_fraction2=None)

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

Parameters:

otherROI/StructureSet/list

ROI with which alignment is to be performed. This can be specified directly as a single ROI. Alternatively, it can be a StructureSet, or a list of ROI/StructureSet objects, in which case the individual ROIs will be combined.

z_fraction1float, default=None

Position along z axis of slice through <self> 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

Position along z axis of slice through <other> 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.

get_volume(units='mm', method=None, force=True)

Get ROI volume. The calculated volume will be cached in self._volume[units] and returned if called again, unless force=True.

Parameters:

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

  • “ml”: return volume in millilitres.

  • “cc”: return volume in cubic centimetres (equivalent to “ml”)

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

If units=”voxels” is requested but this ROI only has contours and no voxel size information, an error will be raised.

methodstr, default=None
Method to use for volume calculation. Can be:
  • “contour”: compute volume by summing areas of shapely polygons on each slice and multiplying by slice thickness.

  • “mask”: compute volume by summing voxels inside the ROI and multiplying by the volume of one voxel.

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

Note that if self.get_volume has already been called with one method, the same cached result will be returned if calling with a different method unless force=True.

forcebool, default=True

If True, the volume will always be recalculated; otherwise, it will only be calculated if it has not yet been cached in self._volume.

get_volume_diff(other, **kwargs)

Get own volume minus volume of other ROI.

get_volume_ratio(other, **kwargs)

Get ratio of another ROI’s volume with respect to own volume.

get_voxel_size()

Load self and get voxel_size.

get_zoom_centre(view)

Get coordinates to zoom in on this ROI.

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.

interpolate_points(n_point=None, dxy=None, smoothness_per_point=0)

Return new ROI object, with interpolated contour points.

Parameters:

n_pointint, default=None

Number of points per contour, after interpolation. This must be set to None for dxy to be considered.

dxyfloat, default=None

Approximate distance required between contour points. This is taken into account only if n_point is set to None. For a contour of length contour_length, the number of contour points is then taken to be max(int(contour_length / dxy), 3).

smoothness_per_pointfloat, default=0

Parameter determining the smoothness of the B-spline curve used in contour approximation for interpolation. The product of smoothness_per_point and the number of contour points (specified directly via n_point, or indirectly via dxy) corresponds to the parameter s of scipy.interpolate.splprep - see documentation at:

https://scipy.github.io/devdocs/reference/generated/scipy.interpolate.splprep.html#scipy.interpolate.splprep

A smoothness_per_point of 0 forces the B-spline to pass through all of the pre-interpolation contour points.

intersect_rois(rois)

Intersect ROI(s) with this ROI.

This method returns the result of the intersection. The original ROIs are left unaltered.

Parameter:

rois: ROI/StructureSet/list

ROI(s) to intersect. This can be a single ROI, a StructureSet, or a list of ROI/StructureSet objects.

is_empty()

Check whether this ROI is empty.

load(force=False)

Load ROI from file or source. The loading sequence is as follows:

1. If self.image is not None, ensure that the image is loaded and assign its geometric properties to this ROI.

  1. Attempt to load data from self.source:

(a) If this is an Image object, the ROI will be created by applying a threshold to the Image’s array. Set self.mask to the thresholded image and self.input_type = “mask”. (b) If self.source is a string, attempt to load from a file conforming to transformix output (.txt extension) or from a dicom structure set (in both cases setting self.input_contours). (c) If transformix or dicom loading fails, attempt to load self.source as an Image object to create an ROI mask. If this finds a valid Image, set self.mask to that image and set self.input_type = “mask”. (d) If self.source is None, do nothing with it.

3. Check whether self.input_contours contains data. This could arise in two scenarios:

(a) The ROI was initialised from a dict of contours, which were assigned to self.input_contours in self.__init(); or (b) A set of contours was successfully loaded from a transformix or dicom file found at self.source in step 1(b).

If input contours are found, these are assigned to self.contours[“x-y”] and self.source_type is set to “contour”. Additionally, if self.image is not None, set self.mask to an array of zeros the same size as the image.

4. Set a flag indicating whether this ROI has contours only (i.e no mask or image from which to draw origin/voxel sizes), and set default geometric calculation method to self.source_type. Set self.loaded to True.

load_transformix_points()

Load point coordinates from file of the format produced by Transformix.

mask_to_contours(mask, view, invert=False)

Create contours from a mask.

match_mask_voxel_size(other, voxel_size=None, voxel_dim_tolerance=0.1)

Ensure that the mask voxel sizes of <self> and <other> match.

The mask voxel_sizes for both may optionally be set to a new common value.

Paramters:

otherskrt.structures.ROI

ROI with which voxel size is to be matched.

voxel_sizetuple, default=None

Voxel size (dx, dy, dz) in mm to be used for ROI masks from which to calculate surface distances. 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.

voxel_dim_tolerancefloat, default=0.1

Maximum accepted value for the absolute difference in voxel size (any dimension) of the ROI masks for them to be considered as having the same voxel size. If a negative value is given, the absolute difference is never below this, forcing creation of new masks with the the specified voxel size. This can be useful for obtaining masks that are just large enough to contain both ROIs, potentially reducing the time for surface-distance calculations.

match_voxel_size(other, *args, **kwargs)
on_slice(view, sl=None, idx=None, pos=None)

Check whether this ROI exists on a given slice.

plot(view='x-y', plot_type=None, sl=None, idx=None, pos=None, ax=None, gs=None, figsize=6, opacity=None, linewidth=None, contour_kwargs=None, mask_kwargs=None, zoom=None, zoom_centre=None, color=None, show=True, save_as=None, include_image=False, no_invert=False, voxel_size=[1, 1], buffer=5, **kwargs)

Plot this ROI as either a mask or a contour.

Parameters:

viewstr, default=”x-y”

Orientation in which to plot. Can be “x-y”, “x-z”, “y-x”, “y-z”, “z-x”, or “z-y”.

plot_typestr, default=”contour”

Plotting type. If None, will be either “contour” or “mask” depending on the input type of the ROI. Options:

  • “contour”

  • “mask”

  • “centroid” (contour with marker at centroid)

  • “filled” (transparent mask + contour)

  • “filled centroid” (filled with marker at centroid)

slint, default=None

Slice number to plot. If none of <sl>, <idx> or <pos> are supplied, the central slice of the ROI will be used.

idxint, default=None

Array index of slice to plot. If none of <sl>, <idx> or <pos> are supplied, the central slice of the ROI will be used.

posfloat, default=None

Position in mm of slice to plot. If none of <sl>, <idx> or <pos> are supplied, the central slice of the ROI will be used.

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=skrt.image._default_figsize

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

opacityfloat, default=None

Opacity to use if plotting mask (i.e. plot types “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.

linewidthfloat, default=None

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

contour_kwargsdict, default=None

Extra keyword arguments to pass to matplotlib contour plotting.

mask_kwargsdict, default=None

Extra keyword arguments to pass to matplotlib mask plotting.

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.

colormatplotlib color, default=None

Color with which to plot the ROI; overrides the ROI’s own color. If None, self.color will be used.

showbool, default=True

If True, the plot will be displayed immediately.

save_asstr, default=None

If set to a string, the plot will be saved to the filename in the string.

include_imagebool, default=False

If True and self.image is not None, the ROI’s image will be plotted in the background.

no_invertbool, default=False

If False, contour plots will be automatically inverted when plotting without an underlying image to account for the y axis increasing in the opposite direction. Otherwise, the plot will be left as it appeared when drawn by matplotlib.

voxel_sizelist, default=[1, 1]

If the ROI does not have an associated image and is described only by contours, this will be the voxel sizes used in the x-y direction when converting the ROI to a mask if a mask plot type is selected.

bufferint, default=5

If the ROI does not have an associated image and is described only by contours, this will be the number of buffer voxels (i.e. whitespace) displayed around the ROI.

`**`kwargs :

Extra keyword arguments to pass to the relevant plot function.

plot_comparison(other, view='x-y', sl=None, idx=None, pos=None, mid_slice_for_both=False, legend=True, save_as=None, names=None, show=True, include_image=False, legend_bbox_to_anchor=None, legend_loc='lower left', voxel_size=[1, 1], buffer=5, **kwargs)

Plot comparison with another ROI. If no sl/idx/pos are given, the central slice of this ROI will be plotted, unless mid_slice_for_both=True, in which case the central slice of both ROIs will be plotted (even though this may not correspond to the same point in space).

Parameters:

otherROI

Other ROI with which to plot comparison.

viewstr, default=”x-y”

Orientation in which to plot ROIs.

slint, default=None

Slice number. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of the ROI will be used.

idxint, default=None

Array index of slice. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of the ROI will be used.

posfloat, default=None

Slice position in mm. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of the ROI will be used.

mid_slice_for_bothbool, default=False

If True and no sl/idx/pos are given, the central slices of both ROIs will be plotted, even if this does not correspond to the same point in space; otherwise, the position of the central slice of this ROI will be plotted for both.

legendbool, default=True

If True, a legend will be added to the plot containing the names of the two ROIs.

save_asstr, default=None

Path to a file at which the plot will be saved. If None, the plot will not be saved.

nameslist, default=None

Custom names to use for the ROI legend in order [this ROI, other ROI]. If None, the names in self.name and roi.name will be used.

showbool, default=True

If True, the plot will be displayed.

voxel_sizelist, default=[1, 1]

If the ROI does not have an associated image and is described only by contours, this will be the voxel sizes used in the x-y direction when converting the ROI to a mask if a mask plot type is selected.

bufferint, default=5

If the ROI does not have an associated image and is described only by contours, this will be the number of buffer voxels (i.e. whitespace) displayed around the ROI.

plot_surface_distances(other, save_as=None, signed=False, **kwargs)

Plot histogram of surface distances.

pos_to_idx(pos, ax, return_int=True, **kwargs)

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.

renamed(name='')

Set ROI name and return self.

resample(*args, **kwargs)
reset_contours(contours=None, most_points=False)

Reset x-y contours to a given dict of slices and contour lists, and ensure that mask and y-x/y-x/y-z/z-x/z-y contours will be recreated. If contours is None, contours will be reset using own x-y contours. If most_points is True, only the contour with most points for each slice is considered.

reset_mask(mask=None)

Set mask to either a numpy array or an Image object, and ensure that contours will be recreated. If mask is None, contours will be reset using own mask.

resize_contours(dxy=0, origin='centroid')

Resize x-y contours by scaling about an origin.

Parameters:

dxy: float, default=0

Nominal positive or negative amount (mm) by which contour (x, y) points are to be moved relative to origin.

origin, str/tuple, default=”centroid”

Keyword (“centroid” or “centre”) or (x, y) tuple indicating the origin with respect to which scaling is to be performed.

resized(margin)

Obtain result of resizing ROI by a specified margin in mm.

Size is increased by a postive margin or decreased by a negative margin. The name of the new ROI is the name of the original plus a suffix indicating the margin.

Parameter:

margin: float, default=1

Size (mm) of positive or negative margin to be added around the ROI.

set_alpha_over_beta(alpha_over_beta=None)

Set ratio for ROI tissue of coefficients of linear-quadratic equation.

Parameter:

alpha_over_betafloat, default=None

Ratio for ROI tissue of coefficients, alpha, beta, of linear-quadratic equation. This ratio is used in calculating biologically effective dose, BED, from physical dose, D, delivered over n equal fractions:

BED = D * (1 + (D/n) / (alpha/beta)).

If None, the biologically effective dose is taken to be equal to the physical dose (beta >> alpha).

set_ax(plot_type, include_image, *args, **kwargs)

Set up axes.

set_color(color=None)

Set plotting color.

set_image(im)

Set self.image to a given image and adjust geometric properties accordingly. Note that self.mask will be removed if the current mask’s shape doesn’t match the image.

set_image_to_dummy(**kwargs)

Assign self.image property to a dummy image covering the area spanned by this ROI. The ROI’s mask and x-z/y-z contours will be cleared so that they will be recreated when get_mask() or get_contours() are next called.

Parameters:

kwargs :

Keyword arguments to pass to self.get_dummy_image() when creating the dummy image. See documentation of ROI.get_dummy_image().

set_name(name='')

Set ROI name.

set_slice_thickness_contours(dz)

Set nominal z spacing of contours.

This may be useful in particular for single-slice ROIs.

slice_to_idx(sl, ax)

Convert a slice number to an array index.

slice_to_pos(sl, ax, standardise=True)

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

split(voxel_size=None, names=None, order='x+')

Split a composite ROI into its components.

A composite ROI may result because phyically separate ROIs are given the same label during manual contouring, or because multiple ROIs are returned by an auto-segmentation algorithm.

The component ROIs are identified by labelling a mask of the composite, using scipy.ndimage.label().

Parameters:

voxel_sizetuple, default=None

Voxel size (x, y) dimensions to use in creating mask for labelling. This can be useful if the ROI source is contour points, and the resolution wanted is greater than is allowed by the voxel size of the ROI image.

names: list, default=None

List of names to be applied to the component ROIs. Names are applied after any ROI ordering.

orderstr, default=’x+’

Specification of way it which ROIs are to be orderd: - ‘x+’ : in order of increasing x value. - ‘x-’ : in order of decreasing x value. - ‘y+’ : in order of increasing y value. - ‘y-’ : in order of decreasing y value. - ‘z+’ : in order of increasing z value. - ‘z-’ : in order of decreasing z value. If any other values is given, no ordering is performed.

split_in_two(axis='x', v0=0, names=None)

Split a composite ROI into two component parts.

Split an ROI into two components, either side of a specified plane. This may be useful, for example, when left and right ROIs have been assigned a common label.

For more general ROI splitting, see skrt.structure.ROI.split(). Note that split() acts on binary masks, whereas split_in_two() acts on contours.

Parameters:

axis‘str’, default=’x’

Axis (‘x’, ‘y’ or ‘z’) perpendicular to plane about which ROI is to be split.

v0float, default=0

Coordinate along selected axis, specifying plane about which ROI is to be split.

names: list, default=None

List of names to be applied to the component ROIs. If None, the name of the composite ROI is used. In all cases, a suffix is added indicating the position of the component relative to the splitting axis.

subtract_rois(rois)

Subtract ROI(s) from this ROI.

This method returns the result of the subtraction. The original ROIs are left unaltered.

Parameter:

rois: ROI/StructureSet/list

ROI(s) to be added. This can be a single ROI, a StructureSet, or a list of ROI/StructureSet objects.

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

Apply three-dimensional similarity transform to ROI.

If the transform corresponds to a translation and/or rotation about the z-axis, and either the roi source type is “dicom” or force-contours is True, the transform is applied to contour points and the roi mask is set as unloaded. Otherwise the transform is applied to the mask and contours are set as unloaded.

The transform is applied in the order: translation, scaling, rotation. The latter two are about the centre coordinates.

Parameters:

force_contoursbool, default=False

If True, and the transform corresponds to a translation and/or rotation about the z-axis, apply transform to contour points independently of the original data source.

For other parameters, see documentation for skrt.image.Image.transform(). Note that the order parameter isn’t available for roi transforms - a value of 0 is used always.

view(include_image=False, voxel_size=[1, 1], buffer=5, **kwargs)

View the ROI.

Parameters:

include_imagebool, default=True

If True and this ROI has an associated image (in self.image), the image will be displayed behind the ROI.

voxel_sizelist, default=[1, 1]

If the ROI does not have an associated image and is described only by contours, this will be the voxel sizes used in the x-y direction when converting the ROI to a mask if a mask plot type is selected.

bufferint, default=5

If the ROI does not have an associated image and is described only by contours, this will be the number of buffer voxels (i.e. whitespace) displayed around the ROI.

write(outname=None, outdir='.', ext=None, overwrite=False, header_source=None, patient_id=None, root_uid=None, verbose=True, header_extras={}, keep_source_rois=True, **kwargs)
class skrt.structures.ROIDefaults(reset=False)

Bases: object

Singleton class for assigning default ROI names and colours.

__init__(reset=False)

Constructor of ROIDefaults singleton class.

get_default_roi_color()

Get a default roi color.

get_default_roi_name()

Get a default name for an ROI.

get_default_structure_set_name()

Get a default name for a structure set.

instance = <skrt.structures.ROIDefaults.__ROIDefaults object>
class skrt.structures.StructureSet(path=None, name=None, image=None, load=True, names=None, keep_renamed_only=False, to_keep=None, to_remove=None, multi_label=False, names_from_json=True, json_names_key=None, json_names_to_exclude=None, colors=None, ignore_dicom_colors=False, auto_timestamp=False, alpha_beta_ratios=None, **kwargs)

Bases: Archive

Class representing a radiotherapy structure set as a collection of regions of interest (ROIs).

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

__init__(path=None, name=None, image=None, load=True, names=None, keep_renamed_only=False, to_keep=None, to_remove=None, multi_label=False, names_from_json=True, json_names_key=None, json_names_to_exclude=None, colors=None, ignore_dicom_colors=False, auto_timestamp=False, alpha_beta_ratios=None, **kwargs)

Load structure set from the source(s) given in <path>.

Parameters:

pathstr/list, default=None

Source(s) of ROIs to load into this structure set. Can be:

  • The path to a single dicom structure set file;

  • The path to a single nifti file containing an ROI mask;

  • A list of paths to nifti files containing ROI masks;

  • The path to a directory containing multiple nifti files

containing ROI masks; - A list of ROI objects; - A list of objects that could be used to initialise an ROI object (e.g. a numpy array).

namestr, default=None

Optional name to assign to this structure set. If None, will attempt to infer from input filename.

imageskrt.image.Image, default=None

Image associated with this structure set. If the input source is a dicom file containing ROI contours, this image will be used when creating ROI binary masks.

loadbool, default=True

If True, ROIs will immediately be loaded from sources. Otherwise, loading will not occur until StructureSet.load() is called.

namesdict/list, default=None

Optional dict of ROI names to use when renaming loaded ROIs. Keys should be desired names, and values should be lists of possible input names or wildcards matching input names.

If multi_label=True, names can also be: (1) a list of names to assign to each label found in order, from smallest to largest; (2) a tuple of names, with the name at index i assigned to label i + 1. (Label 0 corresponds to background.)

to_keeplist, default=None

Optional list of ROI names or wildcards matching ROI names of ROIs to keep in this StructureSet during loading. ROIs not matching will be discarded. Note that the names should reflect those after renaming via the <names> dict. If None, all ROIs will be kept.

to_removelist, default=None

Optional list of ROI names or wildcards matching ROI names of ROIs to remove from this StructureSet during loading. ROIs matching will be discarded. Note that the names should reflect those after renaming via the <names> dict, and removal occurs after filtering with the <to_keep> list. If None, no ROIs will be removed.

multi_labelbool, default=False

If True, will look for multiple ROI masks with different labels inside the array and create a separate ROI from each.

names_from_jsonbool/str/pathlib.Path, default=True

Indicate whether to read ROI names from a JSON file. If True, names will be looked for in a file that has the same path as the structure-set file, but with the suffix “.json”. If a path to a file that exists, look for names in this file. The value associated with the key <json_names_key> of the dictionary read from the JSON file is used to define ROI names. Names in the JSON file may be specified as either an object or an array. These will be read as a dictionary and tuple respectively, interpreted as for <names>. Only considered if <multi_label> is True and <names> is None.

json_names_keystr, default=None

Key to associate with ROI names in dictionary read from JSON file. If None, set to value of skrt.core.Defaults().json_names_key. Used only for structure sets loaded from multi-label NIfTI file.

json_names_to_excludestr/list, default=None

String, or list of strings, indicating name(s) to be disregarded among ROI names read from JSON file. If None, set to value of skrt.core.Defaults().json_names_to_exclude. Matching with names from from file is case insensitive. Used only for structure sets loaded from multi-label NIfTI file.

colorslist/dict

List or dict of colors. If a dict, the keys should be ROI names or wildcards matching ROI names, and the values should be desired colors for ROIs matching that name. If a list, should contain colors which will be applied to loaded ROIs in order.

auto_timestampbool default=False

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

alpha_beta_ratiosdict, default=None

Dictionary where keys are ROI names and values are ratios for ROI tissues of coefficients, alpha, beta, in the linear-quadratic equation. These ratios are used in calculating biologically effective dose, BED, from physical dose, D, delivered over n equal fractions:

BED = D * (1 + (D/n) / (alpha/beta)).

The attribute alpha_over_value is set to the dictionary value for an ROI identified by a key, or is set to None for any other ROIs.

`**`kwargs :

Additional keyword args to use when initialising new ROI objects.

add_plan(plan)

Add a Plan object to be associated with this structure set and its ROIs. This does not affect the structure set associated with the Plan object.

Parameters:

planskrt.dose.Plan

A Plan object to assign to this structure set.

add_roi(source, **kwargs)

Add a single ROI with optional kwargs.

add_rois(sources)

Add additional ROIs from source(s).

clear_plans()

Clear all plan maps associated with this structure set.

clone_attrs(obj, copy_rois=True, copy_roi_data=True)

Assign all attributes of <self> to another object, <obj>, ensuring that ROIs are copied if copy_rois=True.

combine_rois(name=None, roi_names=None, image=None, method=None, intersection=False)

Combine two or more ROIs as a single ROI.

The result represents either the union (default) or the intersection of the input ROIs.

Parameters:

namestr, default=None

Name to be given to the composite ROI. If None, the name assigned is formed by joining together the names of the original ROIs, with the prefix “intersection:” added if <intersection> is set to True.

roi_nameslist, default=None

List of names of ROIs to be combined. If None, all of the structure set’s ROIs are combined.

imageskrt.image.Image, default=None

Image to set for the composite ROI. If None, use the image of the ROI with the first name in <roi_names>.

methodstr, default=None

Method to use for combining ROIs. Can be:

  • “contour”: take unary union of shapely polygons.

  • “mask”: sum binary masks.

  • “auto”: use the default_geom_method of the ROI with the

    first name in <roi_names>.

If None, “auto” is used.

intersectionbool, default=False

If False, the result of combining ROIs represents their union; if True, the result represents their intersection.

containing_image(roi_names=None, image=None, voxel_size=None)

Obtain image containing specified ROIs.

Parameters:

roi_nameslist, default=None

List of strings, specifying names of ROIs to be contained in image. If None, the list returned by self.get_roi_names() will be used.

imageskrt.image.Image, default=None

Template image to be used. If the template image contains the specified ROIs, this image will be returned. Otherwise, a dummy image that fully contains the ROIs will be returned.

voxel_sizetuple, default=None

Three element tuple, specifying the (x, y, z) voxel dimensions (mm) when creating a dummy image that contains the specified ROIs. If None: if <image> is not None, it’s voxel size will be used; otherwise, a voxel size of (1, 1, 1) will be used.

contains(roi_names, in_image=False)

Return whether structure set contains named ROIs, optionally testing whether the ROIs be fully contained in an image.

Parameters:

roi_nameslist/str

Single string, or list of strings, indicating name(s) of ROI(s) to be considered.

in_imagebool/skrt.image.Image, default=False

Specification of whether to test that ROIs are fully contained in an image. If in_image is an Image object, the boolean returned indicates whether all named ROIs are contained within this image. If in_image is True, the boolean returned indicates whether all named ROIs are contained within the image associated with self.

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

Crop all ROIs of StructureSet to specified range in x, y, z.

The parameters xlim, ylim, zlim are passed to each ROI’s crop() method. For explanation of these parameters, see documentation for skrt.structures.ROI.crop().

filter_rois(to_keep=None, to_remove=None)

Keep only the ROIs in the to_keep list and remove any in the to_remove list.

Parameters:

to_keeplist, default=None

List of names of ROIs to keep in the copied StructureSet; all others will be removed. These names can also contain wildcards with the ‘*’ symbol.

to_removelist, default=None

List of names of ROIs to remove from the copied StructureSet; all others will be removed. These names can also contain wildcards with the ‘*’ symbol. Applied after filtering with <to_keep>.

filtered_copy(names=None, name=None, to_keep=None, to_remove=None, keep_renamed_only=False, copy_roi_data=True)

Create a copy of this structure set with ROIs optionally renamed or filtered. Returns a new StructureSet object.

Parameters:

namesdict, default=None

Dictionary of names for renaming ROIs, where the keys are new names and values are lists of possible names of ROIs that should be assigned the new name. These names can also contain wildcards with the ‘*’ symbol.

namestr, default=None

Name for the returned StructureSet.

to_keeplist, default=None

List of names of ROIs to keep in the copied StructureSet; all others will be removed. These names can also contain wildcards with the ‘*’ symbol. Applied after renaming with <names>.

to_removelist, default=None

List of names of ROIs to remove from the copied StructureSet; all others will be removed. These names can also contain wildcards with the ‘*’ symbol. Applied after renaming with <names> and filtering with <to_keep>.

keep_renamed_onlybool, default=False

If True, any ROIs that do not get renamed will be removed from the StructureSet.

copy_roi_databool, default=True

If True, the ROIs in the returned StructureSet will contain copies of the data from the original StructureSet. Otherwise, the new ROIs will contain references to the same data, e.g. the same numpy ndarray object for the mask/same dict for the contours.

find_most_populated_slice(view='x-y')

Find the index of the slice with the most ROIs on it.

get_alpha_beta_ratios()

Get dictionary of ratio of coefficients of linear-quadratic equation.

get_bbox_centre_and_widths(roi_names=None, buffer=None, buffer_units='mm', method=None)

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

Method parameters are passed to skrt.structures.StructureSet.get_extents() to obtain StructureSet extents. For parameter explanations, see skrt.structures.StructureSet.get_extents() documentation.

get_centre(**kwargs)

Get 3D centre of the area covered by ROIs.

get_colors()

Get dict of ROI colors for each name.

get_comparison(other=None, comp_type='auto', consensus_type='majority', **kwargs)

Get pandas DataFrame of comparison metrics vs a single ROI or another StructureSet.

Parameters:

otherROI/StructureSet, default=None

Object to compare own ROIs with. Can either be a single ROI, which will be compared to every ROI in this structure set, or another structure set. If None, a comparison will be performed between the ROIs of this structure set.

comp_typestr, default=”auto”

Method for selecting which ROIs should be compared if other=None or other is a StructureSet. Options are:

  • “all” : compare every ROI in one structure set to every ROI

in the other (removing comparisons of an ROI to itself). - “by_name” : compare every ROI in one structure set to every ROI in the other with the same name. Useful when comparing two structure sets containing ROIs with the same names. - “consensus” : if other=None, compare each ROI in this structure set to the consensus of all other ROIs; otherwise, compare each ROI in this structure set to the consensus of all ROIs in the other structure set. Consensus type is set via the consensus_type argument. - “auto” : if other=None, use “all” comparison. Otherwise, first look for any ROIs with matching names; if at least one matching pair is found, compare via the “by_name” comparison type. If no matches are found, compare via the “all” comparison type.

consensus_typestr, default=”majority vote”

Method for calculating consensus of ROIs if using the “consensus” comparison type. Options are:

  • “majority” : use majority vote of ROIs (i.e. voxels where

at least half of the ROIs exist). - “overlap” : use overlap of ROIs. - “sum” : use sum of ROIs. - “staple” : use the SimpleITK.STAPLE() function to calculate consensus.

htmlbool, default=False

If True, the table will be converted to HTML text color-coded based on ROI colors.

greyed_outbool, default=None

List of ROIs that should be greyed out (given a grey background to their text) if returning an HTML string.

`**`kwargs :

Keyword args to pass to ROI.get_comparison(). See ROI.get_comparison() documentation for details.

get_comparison_pairs(other=None, comp_type='auto', consensus_type='majority', consensus_color='blue')

Get list of ROIs to compare with one another.

get_conformity_index(names=None, **kwargs)

Get conformity index for ROIs of the StructureSet.

Parameters:

nameslist, default=None

List of strings corresponding to ROI names. If non-null, The conformity index is calculated relative for the ROIs with the listed names only. Otherwise, the conformity index is calculated relative to all ROIs in the structure set.

kwargs

Keyword arguments are passed to skrt.structures.get_conformity_index()..get_surface_distances(). See documentation of this function for parameter details.

get_consensus(consensus_type, color='blue', **kwargs)
get_crop_limits(roi_names=None, crop_margins=None, method=None)

Get crop limits corresponding to StructureSet ROI extents plus margins.

The tuples of limits returned, in the order (x, y, z) can be used, for example, as inputs to skrt.image.Image.crop().

This method is similar to the method get_extents(), but allows different margins on each side of the StructureSet.

Parameters:

roi_nameslist, default=None

List of names of ROIs to be considered. If None, all of the structure set’s ROIs are considered.

crop_marginsfloat/tuple, default=None

Float or three-element tuple specifying the margins, in mm, to be added to StructureSet extents. 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).

methodstr, default=None

Method to use for extent calculation. 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.

get_dicom_dataset()

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

get_dummy_image(**kwargs)

Make a dummy image that covers the area spanned by all ROIs in this StructureSet. Returns an Image object.

Parameters:

voxel_sizelist, default=None

Voxel size in mm in the dummy image in the x-y plane, given as [vx, vy]. If <shape> and <voxel_size> are both None, voxel sizes of [1, 1] will be used by default. The voxel size in the z direction is defined by <slice_thickness>.

shapelist, default=None

Number of voxels in the dummy image in the x-y plane, given as [nx, ny]. Only used if <voxel_size> is None. The number of voxels in the z direction will be taken from the number of slices in the x-y contours dictionary.

fill_valint/float, default=1e4

Value with which the voxels in the dummy image should be filled.

bufferint, default=1

Number of empty buffer voxels to add outside the ROI in each direction.

slice_thicknessfloat, default=None

Voxel size in mm in the dummy image in the z direction. If None, the value used is the minimum distance between slice positions in the x-y contours dictionary.

get_extent(**kwargs)

Get min and max extent of all ROIs in the StructureSet.

get_extents(roi_names=None, buffer=None, buffer_units='mm', method=None, origin=None)

Get minimum and maximum extent of StructureSet ROIs, in mm along all three axes, returned in order [x, y, z]. Optionally apply a buffer to the extents such that they cover more than the region of the ROIs.

Parameters:

roi_nameslist, default=None

List of names of ROIs to be considered. If None, all of the structure set’s ROIs are considered.

bufferfloat, default=None

Optional buffer to add to the extents. Units set by buffer_units.

buffer_unitsstr, default=”mm”

Units for buffer, if using. Can be “mm”, “voxels”, or “frac” (which applies buffer as a fraction of total length in each dimension).

methodstr, default=None

Method to use for extent calculation. 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.

origintuple, default=None

Tuple specifying the (x, y, z) coordinates of the point with respect to which extents are to be determined. If None, then (0, 0, 0) is used.

get_geometry(name_as_index=True, html=False, colored=False, greyed_out=None, roi_kwargs={}, **kwargs)

Get pandas DataFrame of geometric properties for all ROIs. If no sl/idx/pos is given, the central slice of each ROI will be used.

Parameters:

name_as_indexbool, default=True

If True, the ROI names will be used as row indices; otherwise, they will be given their own column.

htmlbool, default=False

If True, the table will be converted to HTML text color-coded based on ROI colors.

get_image()

Return Image object associated with this StructureSet.

get_label()

Return label for this StructureSet if loaded from dicom; otherwise, return None.

get_length(ax)

Get length covered by ROIs along an axis.

get_majority_vote(force=False, exclude=None, **kwargs)

Get ROI object representing the majority vote combination of ROIs in this structure set. If <exclude> is set to a string, the ROI with that name will be excluded from the calculation.

Parameters:

forcebool, default=False

If False and majority vote ROI has already been created, the previously computed ROI will be returned. If Force=True, the majority vote ROI will be recreated.

excludestr, default=None

If set to a string, the first ROI in self.rois with that name will be excluded from the combination. This may be useful if comparison of a single ROI with the consensus of all others is desired.

`**`kwargs :

Extra keyword arguments to pass to the creation of the ROI object representing the combination.

get_mask_image(name=None)

Get image object representing mask for all ROIs of structure set.

Parameters:

namestr, default=None

Name to be given to the mask image. If None, the name assigned is the name of the structure set, with suffix “_mask” appended.

get_mid_idx(view='x-y')

Return the array index of the slice that contains the most ROIs.

get_name()

Load self and get name.

get_overlap(force=False, exclude=None, **kwargs)

Get ROI object representing the overlap of ROIs in this structure set. If <exclude> is set to a string, the ROI with that name will be excluded from the calculation.

Parameters:

forcebool, default=False

If False and overlap ROI has already been created, the previously computed ROI will be returned. If Force=True, the overlap ROI will be recreated.

excludestr, default=None

If set to a string, the first ROI in self.rois with that name will be excluded from the combination. This may be useful if comparison of a single ROI with the consensus of all others is desired.

`**`kwargs :

Extra keyword arguments to pass to the creation of the ROI object representing the combination.

get_plans()

Return list of Plan objects associated with this structure set.

get_roi(name)

Get an ROI with a specific name.

get_roi_dict()

Get dict of ROI names and objects.

get_roi_names(original=False, ignore_empty=False)

Get list of names of ROIs in this structure set. If <original> is True, get the original names of the ROIs. If <ignore_empty> is True, omit names of empty ROIs.

get_rois(names=None, ignore_empty=False)

Get list of ROI objects If <names> is given, only the ROIs with those names will be returned.

get_rois_wildcard(wildcard)

Return list of ROIs matching a wildcard expression.

get_series_description()

Return series description for this StructureSet if loaded from dicom; otherwise, return None.

get_staple(force=False, exclude=None, **kwargs)

Get ROI object representing the STAPLE combination of ROIs in this structure set. If <exclude> is set to a string, the ROI with that name will be excluded from the calculation.

The SimpleITK,STAPLE() function used to create the STAPLE ROI sometimes seems to get stuck when dealing with non-overlapping ROIs. To try to avoid this, when two or more ROIs are passed as input, only ROIs overlapping with at least one other ROI are considered. If this excludes all ROIs, a null ROI is returned.

Parameters:

forcebool, default=False

If False and STAPLE ROI has already been created, the previously computed ROI will be returned. If Force=True, the STAPLE ROI will be recreated.

excludestr, default=None

If set to a string, the first ROI in self.rois with that name will be excluded from the combination. This may be useful if comparison of a single ROI with the consensus of all others is desired.

`**`kwargs :

Extra keyword arguments to pass to the creation of the ROI object representing the combination.

get_sum(force=False, exclude=None, **kwargs)

Get ROI object representing the sum of ROIs in this structure set. If <exclude> is set to a string, the ROI with that name will be excluded from the calculation.

Parameters:

forcebool, default=False

If False and sum ROI has already been created, the previously computed ROI will be returned. If Force=True, the sum ROI will be recreated.

excludestr, default=None

If set to a string, the first ROI in self.rois with that name will be excluded from the combination. This may be useful if comparison of a single ROI with the consensus of all others is desired.

`**`kwargs :

Extra keyword arguments to pass to the creation of the ROI object representing the combination.

get_translation_to_align(other, z_fraction1=None, z_fraction2=None)

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

Parameters:

otherROI/StructureSet/list

ROI with which alignment is to be performed. This can be specified directly as a single ROI. Alternatively, it can be a StructureSet, or a list of ROI/StructureSet objects, in which case the individual ROIs will be combined.

z_fraction1float, default=None

Position along z axis of slice through <self> 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

Position along z axis of slice through <other> 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.

has_rois(names=None, include_keys=False)

Determine whether structure set contains specified ROIs, identified by a nominal name or by an alias.

This method returns True if all specified ROI names are matched with the name of an ROI in the structure set, and returns False otherwise. Matching is case insensitive.

namesstr/list/dict

Specification of ROIs: - a single ROI name, optionally including wildcards; - a list of ROI names, each optionally including wildcards; - a dictionary, where keys are nominal ROI names, and values are lists of possible names, optionally including wildcards.

include_keysbool, default=True

If True, consider both keys and values for matching if ROI names are specified as a dictionary. If False, consider values only.

interpolate_points(n_point=None, dxy=None, smoothness_per_point=0)

Return new StructureSet object, with interpolated contour points.

Points are interpolated for each contour of each ROI.

Parameters:

n_pointint, default=None

Number of points per contour, after interpolation. This must be set to None for dxy to be considered.

dxyfloat, default=None

Approximate distance required between contour points. This is taken into account only if n_point is set to None. For a contour of length contour_length, the number of contour points is then taken to be max(int(contour_length / dxy), 3).

smoothness_per_pointfloat, default=0

Parameter determining the smoothness of the B-spline curve used in contour approximation for interpolation. The product of smoothness_per_point and the number of contour points (specified directly via n_point, or indirectly via dxy) corresponds to the parameter s of scipy.interpolate.splprep - see documentation at:

https://scipy.github.io/devdocs/reference/generated/scipy.interpolate.splprep.html#scipy.interpolate.splprep

A smoothness_per_point of 0 forces the B-spline to pass through all of the pre-interpolation contour points.

load(sources=None, force=False)

Load structure set from source(s). If None, will load from own self.sources.

missing(roi_names, in_image=False)

Identify among named ROIs those that are missing from structure set, or are not fully contained in an image.

Parameters:

roi_nameslist/str

Single string, or list of strings, indicating name(s) of ROI(s) to be considered.

in_imagebool/skrt.image.Image, default=False

Specification of whether to test that ROIs are fully contained in an image. If in_image is in Image object, an ROI is identified as missing if not contained within this image. If in_image is True, an ROI is identified as missing if not contained within the image associated with self.

order_rois(order='x+')

Order ROIs by one of their centroid coordinates.

Parameter:

orderstr, default=’x+’

Specification of way it which ROIs are to be orderd: - ‘x+’ : in order of increasing x value. - ‘x-’ : in order of decreasing x value. - ‘y+’ : in order of increasing y value. - ‘y-’ : in order of decreasing y value. - ‘z+’ : in order of increasing z value. - ‘z-’ : in order of decreasing z value.

plot(view='x-y', plot_type='contour', sl=None, idx=None, pos=None, ax=None, opacity=None, linewidth=None, include_image=True, centre_on_roi=None, show=True, save_as=None, legend=False, legend_bbox_to_anchor=None, legend_loc='lower left', consensus_type=None, exclude_from_consensus=None, consensus_color='blue', consensus_linewidth=None, voxel_size=[1, 1], buffer=5, **kwargs)

Plot the ROIs in this structure set.

If consensus_type is set to any of ‘majority’, ‘sum’, ‘overlap’, or ‘staple’, the conensus contour will be plotted rather than individual ROIs. If ‘exclude_from_consensus’ is set to the name of an ROI, that ROI will be excluded from the consensus calculation and plotted individually.

plot_comparisons(other=None, comp_type='auto', outdir=None, legend=True, names=None, legend_bbox_to_anchor=None, legend_loc='lower left', **kwargs)

Plot comparison pairs.

plot_consensus(consensus_type, view='x-y', sl=None, idx=None, pos=None, rois_in_background=False, color=None, voxel_size=[1, 1], buffer=5, include_image=False, show=True, **kwargs)

Plot the consensus contour, with all ROIs in grey behind it if rois_in_background=True.

plot_surface_distances(other, outdir=None, signed=False, comp_type='auto', **kwargs)

Plot surface distances for all ROI pairs.

print_rois()
recolor_rois(colors)

Set colors of ROIs using a list or dict given in <colors>.

Parameters:

colorslist/dict

List or dict of colors. If a dict, the keys should be ROI names or wildcards matching ROI names, and the values should be desired colors for ROIs matching that name. If a list, should contain colors which will be applied to loaded ROIs in order.

rename_rois(names=None, first_match_only=True, keep_renamed_only=False)

Rename ROIs in this StructureSet. <first_match_only> is True, only the first ROI matching the possible matches will be renamed.

Parameters:

namesdict, default=None

Dictionary of names for renaming ROIs, where the keys are new names and values are lists of possible names of ROIs that should be assigned the new name. These names can also contain wildcards with the ‘*’ symbol.

first_match_onlybool, default=True

If True, only the first ROI matching the possible names in the values of <names> will be renamed; this prevents name duplication if multiple ROIs in the StructureSet are a match.

keep_renamed_onlybool, default=False

If True, any ROIs that do not get renamed will be removed from the StructureSet.

renamed(name='')

Set StructureSet name and return self.

reset()

Reload structure set from original source(s).

reset_contours(contours=None, most_points=False)

Reset x-y contours for ROIs of structure set.

Parameters:

contoursdict, default=None

Dictionary where keys are ROI names and values are dictionaries of slice and contour lists. If None, an empty dictionary is used. If an ROI has a name not included in the top-level dictionary, or has a name with associated value None, the ROI contours will be reset using the ROI’s own x-y contours.

most_pointsbool, default=False

If True, only the contour with most points for each slice is retained after resetting. If False, all contours for each slice are retained.

set_alpha_beta_ratios(alpha_beta_ratios=None, set_as_default=True)

Set ratios for ROI tissues of coefficients of linear-quadratic equation.

Optionally input values for ratios as structure-set default.

Parameter:

alpha_beta_ratiosdict, default=None

Dictionary where keys are ROI names and values are ratios for ROI tissues of coefficients, alpha, beta, in the linear-quadratic equation. These ratios are used in calculating biologically effective dose, BED, from physical dose, D, delivered over n equal fractions:

BED = D * (1 + (D/n) / (alpha/beta)).

The attribute alpha_over_value is set to the dictionary value for an ROI identified by a key, or is set to None for any other ROIs. If this parameter is set to None, values are set from self.alpha_beta_ratios.

set_as_defaultbool, default=True

If True, and alpha_beta_ratios isn’t None, set self.alpha_beta_ratios to the value of alpha_beta_ratios.

set_image(image, add_to_image=True)

Set image for self and all ROIs. If add_to_image is True, image.add_structure_set(self) will also be called.

set_image_to_dummy(**kwargs)

Set image for self and all ROIs to be a dummy image covering the region containing all ROIs in the structure set. The mask and x-z/y-z contours of each ROI will be cleared, so that they will be recreated when get_mask() or get_contours() are next called.

Parameters:

kwargs :

Keyword arguments to pass to self.get_dummy_image() when creating the dummy image. See documentation of StructureSet.get_dummy_image().

set_name(name='')

Set StructureSet name.

split_rois_in_two(roi_names=None, axis='x', v0=0)

Replace composite ROIs in structure set by two component parts.

Each ROI considered is split into two components, either side of a specified plane. This may be useful, for example, when left and right ROIs have been assigned a common label.

The component ROIs have the same name as the composite from which they’re derived, with a suffix added that indicates the position of the component relative to the splitting axis.

Parameters:

roi_nameslist/str, default=None

Single string, or list of strings, indicating name(s) of ROI(s) to be considered. if None, the original structure set is left unmodified.

axis‘str’, default=’x’

Axis (‘x’, ‘y’ or ‘z’) perpendicular to plane about which each ROI is to be split.

v0float, default=0

Coordinate along selected axis, specifying plane about which each ROI is to be split.

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

Apply three-dimensional similarity transform to structure-set ROIs.

If the transform corresponds to a translation and/or rotation about the z-axis, and either the roi source type is “dicom” or force-contours is True, the transform is applied to contour points and the roi mask is set as unloaded. Otherwise the transform is applied to the mask and contours are set as unloaded.

The transform is applied in the order: translation, scaling, rotation. The latter two are about the centre coordinates.

Parameters:

force_contoursbool, default=False

If True, and the transform corresponds to a translation and/or rotation about the z-axis, apply transform to contour points independently of the original data source.

nameslist/None, default=False

List of ROIs to which transform is to be applied. If None, transform is applied to all ROIs.

For other parameters, see documentation for skrt.image.Image.transform(). Note that the order parameter isn’t available for structure-set transforms - a value of 0 is used always.

view(include_image=True, rois=None, voxel_size=[1, 1], buffer=5, **kwargs)

View the StructureSet.

Parameters:

include_imagebool, default=True

If True and this StructureSet has an associated image (in self.image), the image will be displayed behind the ROIs.

roisStructureSet/list, default=None

Any other ROIs or StructureSets to include in the plot.

voxel_sizelist, default=[1, 1]

If the StructureSet does not have an associated image and has ROIs described only by contours, this will be the voxel sizes used in the x-y direction when converting ROIs to masks if a mask plot type is selected.

bufferint, default=5

If the StructureSet does not have an associated image and has ROIs described only by contours, this will be the number of buffer voxels (i.e. whitespace) displayed around the extent of the ROIs.

write(outname=None, outdir='.', ext=None, overwrite=False, verbose=True, header_source=None, patient_id=None, patient_position=None, root_uid=None, header_extras={}, multi_label=False, names_to_json=True, json_names_key='labels', names=None, voxel_size=None, **kwargs)

Write structure set.

The output may be a single DICOM file, a directory containing a NIfTI file for each ROI, or a single (multi-label) NIfTI file.

Parameters: outname : str, default=None

Name to use for output file. If None, and a DICOM file or multi-label NIfTI file is to be written, a name including modality and timestamp is generated.

outdirstr/pathlib.Path, default=None

Path to directory where output is to be written.

ext: str, default=None

File extension specifying format for output file(s). Valid values are “.dcm”, “.nii.gz”, “nii”. If None, the extension is taken from <outname>.

overwritebool, default=False

If True, delete any pre-existing DICOM files from output directory before writing.

verbosebool, default=True

If True, print information about output writing.

header_sourcestr/pydicom.dataset.FileDataset/None, default=None

Source from which to create DICOM header. This can be: (a) a path to a dicom file, which will be used as the header; (b) a path to a directory containing dicom files, where

the first file alphabetically will be used as the header;

  1. a pydicom.dataset.FileDataset object;

  2. None, in which case a header will be created from scratch, inculding new UIDs.

Ignored when not writing DICOM output.

patient_idstr, default=None

Patient identifier. Ingored when not writing DICOM output.

patient_positionstr, default=None

Indicator of patient position relative to imaging equipment. Examples include: “HFS” (head first, supine), “FFP” (feet first, prone), “FFS” (feet first, supine). If None, use “HFS”. Ignored when not writing DICOM output.

root_uidstr, default=None

Root to be used in Globally Unique Identifiers (GUIDs). This should uniquely identify the institution or group generating the GUID. If None, the value of pydicom.uid.PYDICOM_ROOT_UID is used. Ignored when not writing DICOM output.

header_extrasdict, default=None

Dictionary of attribute-value pairs for applying arbitary updates to DICOM header. Ignored when not writing DICOM output.

multi_labelbool, default=False

If True, and writing NIfTI output, write a single file, with a different label for each ROI. ROIs are labelled by consecutive integers, starting from 1, in the order specified by <names>. Ignored when not writing NIfTI output.

names_to_jsonbool/str/pathlib.Path, default=True

Indicate whether to write ROI names to a JSON file when writing multi-label NIfTI output. If True, names will be written to a file that has the same path as the structure-set output file, but with the suffix “.json”. If a path, names will be written to a file at this path. ROI names are written as a tuple, associated with the dictionary key <json_names_key>. Ignored if <multi_label> is False.

json_names_keystr, default=”roi_names”

Key to associate with ROI names in dictionary written to JSON file. If None, set to value of skrt.core.Defaults().json_names_key.

nameslist, default=None

List of strings, specifying names of ROIs to be written to multi-label NIfTI file, in the order in which they are to be labelled. If None, the list of names returned by self.get_roi_names() is used. Ignored when not writing multi-label NIfTI output.

voxel_sizetuple, default=None

Three element tuple, specifying the (x, y, z) voxel dimensions (mm) when creating a dummy image for writing to multi-label NIfTI file, for case where structure set doesn’t have an associated image. If None, a voxel size of (1, 1, 1) will be used. Ignored when not writing multi-label NIfTI output.

**kwargs

Keyword arguments passed to skrt.structures.ROI.write() when writing single NIfTI file per ROI.

class skrt.structures.StructureSetIterator(structure_set)

Bases: object

__init__(structure_set)
skrt.structures.best_text_color(red, green, blue)
skrt.structures.compare_roi_pairs(pairs, html=False, name_as_index=True, greyed_out=None, colored=False, roi_kwargs={}, **kwargs)
skrt.structures.contour_to_polygon(contour)

Convert a list of contour points to a Shapely polygon, ensuring that the polygon is valid.

skrt.structures.create_dummy_image(extents, slice_thickness, shape=None, voxel_size=None, fill_val=10000.0, buffer=2)

Make a dummy image that covers the area spanned by <extents> plus a buffer.

Parameters:

extentslist

List of [min, max] extents in mm along each of the three axes in order [x, y, z].

slice_thicknessfloat

Slice thickness in mm.

voxel_sizelist, default=None

Voxel size in mm in the dummy image in the x-y plane, given as [vx, vy]. If <shape> and <voxel_size> are both None, voxel sizes of [1, 1] will be used by default. The voxel size in the z direction will be taken from the minimum distance between slice positions in the x-y contours dictionary.

shapelist, default=None

Number of voxels in the dummy image in the x-y plane, given as [nx, ny]. Only used if <voxel_size> is None. The number of voxels in the z direction will be taken from the number of slices in the x-y contours dictionary.

fill_valint/float, default=1e4

Value with which the voxels in the dummy image should be filled.

bufferfloat, default=2

Buffer amount of whitespace in mm to add outside the ROI in each direction.

skrt.structures.create_majority_vote(rois, **kwargs)

Create majority vote ROI from list of ROIs.

skrt.structures.create_roi_overlap(rois, **kwargs)

Create ROI from overlap of list of ROIs.

skrt.structures.create_roi_sum(rois, **kwargs)

Create ROI from sum of list of ROIs.

skrt.structures.create_staple(rois, **kwargs)

Create STAPLE ROI from list of ROIs.

The SimpleITK,STAPLE() function used to create the STAPLE ROI sometimes seems to get stuck when dealing with non-overlapping ROIs. To try to avoid this, when two or more ROIs are passed as input, only ROIs overlapping with at least one other ROI are considered. If this excludes all ROIs, a null ROI is returned.

skrt.structures.create_structure_sets_from_nifti(path, load=True, json_names_key=None, json_names_to_exclude=None, nifti_exts=None, json_exts=None)

Create StructureSet objects from NIfTI files.

If the path to a NIfTI file is passed, an attempt will be made to instantiate a StructureSet object from this file. If a path to a directory is passed, an attempt will be made to instantiate StructureSet objects from all NIfTI files in this directory.

The logic for creating StructureSet objects is follows:

  1. A StructureSet is created for each NIfTI file considered for which there is an accompanying JSON file of the same name (excluding suffixes), with the ROI names taken from the JSON file.

  2. If only a single NIfTI file is considered, and its directory contains a single JSON file from which ROI names can be read (i.e. the JSON file include <json_names_key> as a dictionary key), a StructureSet is created for the NIfTI file, with names taken from the JSON file.

  3. A StructureSet is created for each remaining NIfTI file that contains multiple labels, where if the labels are 1, 2, 4 the corresponding ROI names will be “ROI 1”, “ROI 2”, “ROI 4”.

  4. A StructureSet is created from all remaining NIfTI files, where the name of each ROI will be the same as the filename (without suffixes) of its source file.

Parameters:

path: str/pathlib.Path

Path to a NIfTI file representing a structure set, or to a directory containing one or more NIfTI files representing structure sets.

loadbool, default=True

If True, structure-set ROIs will immediately be loaded from sources. Otherwise, loading will not occur until an operation is performed until StructureSet.load() is called.

json_names_key: str, default=None

Key to associate with ROI names in dictionaries read from JSON files. If None, set to value of skrt.core.Defaults().json_names_key. Used only when structure sets are created from multi-label NIfTI files.

json_names_to_exclude: str/list, default=None

String, or list of strings, indicating name(s) to be disregarded among ROI names read from JSON files. If None, set to value of skrt.core.Defaults().json_names_to_exclude. Matching with names from from file is case insensitive. Used only when structure sets are created from multi-label NIfTI files.

nifti_exts: str/list, default=None

String, or list of strings, indicating filename suffix(es) of files to be identified as NIfTI files. If None, set to value of skrt.core.Defaults().nifti_exts.

json_exts: str/list, default=None

String, or list of strings, indicating filename suffix(es) of files to be identified as JSON files. If None, set to value of skrt.core.Defaults().json_exts.

skrt.structures.df_to_html(df)

Convert a pandas DataFrame to html.

skrt.structures.expand_slice_stats(slice_stats=None, default_by_slice=None)

Expand specification of statistics to calculate for ROI comparison metrics evaluated slice by slice.

A dictionary is returned, where keys give the slices to be considered for calculating statistics, and values are lists of metrics.

Parameters:

slice_statsstr/list/dict, default=None

Specification of statistics to be calculated relative to slice-by-slice metric values.

A statistic is specified by the name of the function for its calculation in the Python statistics module:

https://docs.python.org/3/library/statistics.html

For its use here, the relevant function must require a single-variable input, must not require any keyword arguments, and must return a single number.

Available options include: “mean”, “median”, “mode”, “stdev”.

Statistics to be calculated can be specified using any of the following:

  • String specifying single statistic to be calculated, with slices considered as given by <default_by_slice>, for example: “mean”;

  • List specifying multiple statistics to be calculated, with slices considered as given by <default_by_slice>, for example: [“mean”, “stdev”];

  • Dictionary where keys specify slices to be considered, and values specify statistics (string or list), for example: {“union”: [“mean”, “stdev”]}. Valid slice specifications are as listed for <default_by_slice>.

default_by_slice: str, default=None

Default specification of slices to be considered when calculating slice-by-slice statistics for a metric comparing two ROIs, roi1 and roi2. The valid specifications are:

  • “left”: consider only slices containing roi1;

  • “right”: consider only slices containing roi2;

  • “union”: consider slices containing either of roi1 and roi2;

  • “intersection”: consider slices containing both roi1 and roi2.

If None, use skrt.core.Defaults().by_slice

skrt.structures.get_all_rois(objs=None)

Create list of ROIs from arbitrary combination of ROIs and StructureSets.

Parameters:

objsROI/StructureSet/list, default=None

Object(s) from which a list of ROIs is to be created. The object(s) can be a single skrt.structures.ROI object, a single skrt.structures.StructureSet object, or a list containing any combination of ROI and StructureSet objects.

skrt.structures.get_by_slice_methods()

Get list of methods for defining slices to be considered for slice-by-slice ROI comparisons.

skrt.structures.get_colored_roi_string(roi, grey=False, color=None)

Get ROI name in HTML with background color from roi.color. If grey=True, the background color will be grey.

skrt.structures.get_comparison_metrics(centroid_components=False, slice_stats=None, default_by_slice=None, view='x-y')

Get list of comparison metrics.

All metrics listed here should be recognised by ROI.get_comparison(), and all metrics recognised by ROI.get_comparison() should be listed here.

Parameters:

centroid_componentsbool, default=False

If True, replace metrics “centroid” and “centroid_slice” by the metrics for their components.

slice_statsstr/list/dict, default=None

Specification of statistics to be calculated relative to slice-by-slice metric values.

A statistic is specified by the name of the function for its calculation in the Python statistics module:

https://docs.python.org/3/library/statistics.html

For its use here, the relevant function must require a single-variable input, must not require any keyword arguments, and must return a single number.

Available options include: “mean”, “median”, “mode”, “stdev”.

Statistics to be calculated can be specified using any of the following:

  • String specifying single statistic to be calculated, with slices considered as given by <default_by_slice>, for example: “mean”;

  • List specifying multiple statistics to be calculated, with slices considered as given by <default_by_slice>, for example: [“mean”, “stdev”];

  • Dictionary where keys specify slices to be considered, and values specify statistics (string or list), for example: {“union”: [“mean”, “stdev”]}. Valid slice specifications are as listed for <default_by_slice>.

default_by_slice: str, default=None

Default specification of slices to be considered when calculating slice-by-slice statistics for a metric comparing two ROIs, roi1 and roi2. The valid specifications are:

  • “left”: consider only slices containing roi1;

  • “right”: consider only slices containing roi2;

  • “union”: consider slices containing either of roi1 and roi2;

  • “intersection”: consider slices containing both roi1 and roi2.

If None, use skrt.core.Defaults().by_slice

viewstr, default=”x-y”

Orientation to consider when taking centroid components relative to a slice. Can be “x-y”, “x-z”, “y-x”, “y-z”, “z-x”, or “z-y”.

skrt.structures.get_conformity_index(rois, ci_type='gen', single_slice=False, view='x-y', sl=None, idx=None, pos=None, method=None, flatten=False)

Get conformity index for two or more ROIs.

The conformity index may be calculated globally or for a single slice.

This function returns either the value of one of the three types of conformity index (“gen” (for generalised), “pairs”, “common”) referred to in: https://doi.org/10.1088/0031-9155/54/9/018 or a skrt.core.Data object with the values of all three. For the case of two ROIs, the three metrics are all equivalent to the Jaccard conformity index.

Parameters:

roislist

List of two or more skrt.structures.ROI objects for which conformity index is to be calculated.

ci_type: str, default=”gen”

Type of conformity index to be returned, from “gen” (for generalised), “pairs”, “common”. If set to “all”, a skrt.core.Data object with values for the three types of conformity index is returned.

single_slicebool, default=False

If False, the global 3D Dice score of the full ROIs will be returned; otherwise, the 2D Dice score on a single slice will be returned.

viewstr, default=”x-y”

Orientation of slice on which to get Dice score. Only used if single_slice=True. If using, <ax> must be an axis that lies along the slice in this orientation.

slint, default=None

Slice number. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of this ROI will be used.

idxint, default=None

Array index of slice. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of this ROI will be used.

posfloat, default=None

Slice position in mm. If none of <sl>, <idx> or <pos> are supplied but <single_slice> is True, the central slice of this ROI will be used.

methodstr, default=None

Method to use for Dice score calculation. Can be: - “contour”: get intersections and areas of shapely contours. - “mask”: count intersecting voxels in binary masks. - None: use the method set in self.default_geom_method. For more than two ROIs and <ci_type> “common”, only the “mask” method is implemented.

flattenbool, default=False

If True, all slices will be flattened in the given orientation and the Dice score of the flattened slices will be returned. Only available if method=”mask”.

skrt.structures.get_consensus_types()

Get list of consensus types.

All consensus types listed here should be recognised by StructureSet.get_consensus(), and all consensus types recognised by StructureSet.get_consensus should be listed here.

skrt.structures.get_dicom_sequence(ds=None, basename='')
skrt.structures.get_intersection(polygons)

Return intersection of a collection of polygons.

If the input polygons have no intersection, None is returned.

Parameter:

polygons: list

List of shapely.geometry.polygon.Polygon and/or shapely.geometry.multipolygon.MultiPolygon objects for which the intersection is to be calculated.

skrt.structures.get_metric_method(metric)

Map between metric identifier as listed in get_comparison_metrics() and name of ROI method for calculating the metric.

This function is used in ROI.get_metric_by_slice() to determine the method to be called for each metric.

skrt.structures.get_roi_slice(roi, z_fraction=1, suffix=None)

Get ROI object corresponding to x-y slice through input ROI.

Parameters:

roiskrt.structures.ROI

ROI object for which slice is to be obtained.

z_fractionfloat, default=1

Position along z axis at which to take slice through ROI. The position is specified as the fractional 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.

suffixstr, default=None

Suffix to append to name of input ROI, to form name of output ROI. If None, append z_fraction, with value given to two decimal places.

skrt.structures.get_slice_positions(roi1, roi2=None, view='x-y', position_as_idx=False, method=None)

Get ordered list of slice positions for either or both of a pair of ROIs.

Parameters:

roi1skrt.structures.ROI

ROI, or one of a pair of ROIs, for which slice information is to be obtained.

roi2skrt.structures.ROI, default=None

If not None, second in a pair of ROIs for which slice information is to be obtained.

viewstr, default=”x-y”

View in which to obtain slices.

position_as_idxbool, default=False

If True, return positions as slice indices; if False, return positions as slice z-coordinates (mm).

method: str, default=None

String specifying slices for which positions are to be obtained, for ROIs roi1, roi2:

  • “left” (or roi2 is None): return positions of slices containing roi1;

  • “right”: return positions of slices containing roi2;

  • “union”: return positions of slices containing either roi1 or roi2;

  • “intersection”: return positions of slices containing both roi1 and roi2.

If None, value of skrt.core.Defaults().by_slice is used.

skrt.structures.get_structuring_element(radius=1, voxel_size=(1, 1, 1))

Obtain spherical structuring element, taking into account voxel size.

Parameters:

radius: float, default=1

Radius (mm) of spherical structuring element to be generated.

voxel_size: tuple, default=(1, 1, 1)

Voxel size (mm) along (x, y, z) axes.

skrt.structures.get_translation_to_align(roi1, roi2, z_fraction1=None, z_fraction2=None)

Determine translation for aligning <roi1> to <roi2>.

Parameters:

roi1ROI/StructureSet/list

ROI that is to be translation to achieve the alignment. This can be specified directly as a single ROI. Alternatively, it can be a StructureSet, or a list of ROI/StructureSet objects, in which case the individual ROIs will be combined.

roi2ROI/StructureSet/list

ROI with which alignment is to be performed. This can be specified directly as a single ROI. Alternatively, it can be a StructureSet, or a list of ROI/StructureSet objects, in which case the individual ROIs will be combined.

z_fraction1float, default=None

Position along z axis of slice through <roi1> 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

Position along z axis of slice through <roi2> 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.structures.interpolate_points_single_contour(source=None, n_point=None, dxy=None, smoothness_per_point=0)

Interpolate points for a single contour.

Parameters:

sourceshapely.polygon.Polygon/np.ndarray/list, default=None

Contour representation as either a shapely Polygon, a numpy array of [x, y] pairs or a list of [x, y] pairs. The returned contour has the same representation.

n_pointint, default=None

Number of points to define contour, after interpolation. This must be set to None for dxy to be considered.

dxyfloat, default=None

Approximate distance required between contour points. This is taken into account only if n_point is set to None. For a contour of length contour_length, the number of contour points is then taken to be max(int(contour_length / dxy), 3).

smoothness_per_pointfloat, default=0

Parameter determining the smoothness of the B-spline curve used in contour approximation for interpolation. The product of smoothness_per_point and the number of contour points (specified directly via n_point, or indirectly via dxy) corresponds to the parameter s of scipy.interpolate.splprep - see documentation at:

https://scipy.github.io/devdocs/reference/generated/scipy.interpolate.splprep.html#scipy.interpolate.splprep

A smoothness_per_point of 0 forces the B-spline to pass through all of the pre-interpolation contour points.

skrt.structures.load_rois_dicom(path, names=None)

Load ROI(s) from a dicom structure set file. <name> can be a single name or list of names of ROIs to load.

skrt.structures.match_rois(roi1, roi2, ax='z', strategy=2, inplace=False)

Process pair of ROIs, to match extents along one or more axes.

One or both ROIs may be cropped to match the other. Cropping may be performed on the input ROIs, or on clones of these. In the latter case, the originals are left unchanged.

Parameters: roi1, roi2 : skrt.structures.ROI

ROIs to be matched with one another.

axstr/int/list, default=”z”

Specification of a single axis, or of a list of axes, along which ROI extents are to be matched. Each axis is specified as one of [“x”, “y”, “z”] or [0, 1, 2].

strategyint, default=1

Strategy to use for matching ROI extents along each specified axis:

  • 0 : Crop roi1 to the extents of roi2.

  • 1 : Crop roi2 to the extents of roi1.

  • 2Crop roi1 to the extents of roi2,

    then crop roi2 to the extents of roi1.

For a value other than 0, 1, 2, no extent matching is performed.

inplacebool, default=False

If True, crop the input ROIs. If False, clone the input ROIs, and crop these.

skrt.structures.polygon_to_contour(polygon)

Convert a Shapely polygon to a list of contour points.

Parameter:

polygon: shapely.geometry.polygon

Shapely polygon.

z_polygon: z coordinate at which polygon is defined.