skrt.segmentation module
Classes and functions relating to image segmentation.
This module implements atlas-based segmentation, where an atlas is a reference image, for which regions of interest (ROIs) have been segmented in some way.
In single-atlas segmentation, a single atlas and a target image, which is the image to be segmented, are registered to one another. Atlas segmentations are then mapped to the target image, using the registration transform. An ROI may be represented as a binary mask or as sets of contour points, resulting in two strategies for mapping ROIs:
atlas and target are taken as fixed and moving image respectively for registration, then ROI contour points are pushed from atlas to target;
target and atlas are taken as fixed and moving image respectively for the registration, then ROI binary masks are pulled from atlas to target.
In multi-atlas segmentation, single-atlas segmentation is performed multiple times, using a different atlas for each segmentation, then the results from the individual segmentations are combined in some way.
The following classes are defined:
MultiAtlasSegmentation() : class for performing multi-atlas segmentation.
SasTuner() : class for varying parameters in a single-atlas segmentation, comparing results for each set of parameters with reference segmentations.
SingleAtlasSegmentation() : class for performing single-atlas segmentation;
The following are utility functions used by SingleAtlasSegmentation() and MultiAtlasSegmentation():
ensure_dict() : Try to return a dictionary based on given input.
ensure_image() : Try to return an Image based on given input.
ensure_structure_set() : Try to return a StructureSet based on given input.
get_atlases() : Obtain dictionary of atlas tuples (structure set and associated image).
get_contour_propagation_strategies() : Return list of contour propagation strategies for registration engine.
get_fixed_and_moving() : Order target and atlas images as fixed and moving, depending on strategy.
get_option() : Apply logic for selecting an allowed option.
get_options() : Apply logic for selecting a list of allowed options.
get_segmentation_steps() : Return list of segmentation steps.
get_steps() : Get list of segmentation steps to run.
get_strategy() : Apply logic for selecting an allowed strategy for contour propagation.
get_structure_set_index() : Get positive index identifying structure set associated with an image.
load_mas() : Load MultiAtlasSegmentation instance from work directory.
load_sas() : Load SingleAtlasSegmentation instance from work directory.
select_atlases() : Select atlases to register against target.
- class skrt.segmentation.MultiAtlasSegmentation(im1=None, im2=None, ss1=None, ss2=None, log_level=None, workdir='segmentation_workdir', overwrite=False, engine=None, engine_dir=None, auto=False, auto_step=None, auto_strategies=None, auto_reg_setup_only=False, default_step=None, default_strategy='pull', roi_names=None, metrics=None, default_slice_stats=None, default_by_slice=None, consensus_types='majority', default_consensus_type='majority', max_workers=1, **kwargs)
Bases:
Data
- __init__(im1=None, im2=None, ss1=None, ss2=None, log_level=None, workdir='segmentation_workdir', overwrite=False, engine=None, engine_dir=None, auto=False, auto_step=None, auto_strategies=None, auto_reg_setup_only=False, default_step=None, default_strategy='pull', roi_names=None, metrics=None, default_slice_stats=None, default_by_slice=None, consensus_types='majority', default_consensus_type='majority', max_workers=1, **kwargs)
Constructor of Data class, allowing initialisation of an arbitrary set of attributes.
Parameters:
- get_comparison(consensus_types=None, atlas_ids=True, id1=None, to_keep=None, strategies=None, steps=None, reg_steps=None, force=True, metrics=None, slice_stats=None, default_by_slice=None, voxel_size=None, name_as_index=False, atlas_ids_to_compare=False, combination_length=None, **kwargs)
- get_consensus(atlas_ids=None, strategy=None, step=None, reg_step=None, consensus_type=None, force=False)
- get_sas(atlas_id=None)
- get_sas_segmentations(atlas_ids=True, strategy=None, step=None, reg_step=None, force=False)
- get_similarity_scores(atlas_ids=None, strategy=None, step=None, roi_name=None, reg_step=None, force=False, max_keep=None, **kwargs)
- segment(atlas_ids=None, strategy=None, step=None, consensus_types=None, force=False, reg_setup_only=False)
- set_consensuses(atlas_ids=None, strategy=None, step=None, reg_step=None, consensus_types=None, force=False)
- class skrt.segmentation.SasTuner(pfiles1_variations=None, pfiles2_variations=None, keep_segmentations=False, **kwargs)
Bases:
Data
- __init__(pfiles1_variations=None, pfiles2_variations=None, keep_segmentations=False, **kwargs)
Constructor of Data class, allowing initialisation of an arbitrary set of attributes.
Parameters:
- class skrt.segmentation.SingleAtlasSegmentation(im1=None, im2=None, ss1=None, ss2=None, log_level=None, workdir='segmentation_workdir', overwrite=False, engine=None, engine_dir=None, auto=False, auto_step=None, auto_strategies=None, auto_reg_setup_only=False, default_step=-1, default_strategy='pull', roi_names=None, ss1_index=-1, ss2_index=-1, ss1_name='Filtered1', ss2_name='Filtered2', initial_crop_focus=None, initial_crop_margins=None, initial_crop_about_centre=False, initial_alignment=None, initial_transform_name=None, crop_to_match_size1=True, voxel_size1=None, bands1=None, pfiles1=None, most_points1=True, roi_z_fraction=None, default_roi_z_fraction=None, roi_crop_margins=None, default_roi_crop_margins=10, roi_crop_about_centre=None, default_roi_crop_about_centre=False, roi_pfiles=None, crop_to_match_size2=True, voxel_size2=None, default_roi_bands=None, roi_bands=None, pfiles2=None, most_points2=True, capture_output=False, keep_tmp_dir=False, metrics=None, default_slice_stats=None, default_by_slice=None, write_archive=True, im1_margins=None, im2_margins=None, margins_units='mm')
Bases:
Data
Class for performing single-atlas segmentation.
Methods:
_init__() : Create instance of SingleAtlasSegmentation class.
segment() :
segment_roi() :
segment_structure_set() :
get_auto_steps() :
get_registration() :
() :
() :
() :
() :
- __init__(im1=None, im2=None, ss1=None, ss2=None, log_level=None, workdir='segmentation_workdir', overwrite=False, engine=None, engine_dir=None, auto=False, auto_step=None, auto_strategies=None, auto_reg_setup_only=False, default_step=-1, default_strategy='pull', roi_names=None, ss1_index=-1, ss2_index=-1, ss1_name='Filtered1', ss2_name='Filtered2', initial_crop_focus=None, initial_crop_margins=None, initial_crop_about_centre=False, initial_alignment=None, initial_transform_name=None, crop_to_match_size1=True, voxel_size1=None, bands1=None, pfiles1=None, most_points1=True, roi_z_fraction=None, default_roi_z_fraction=None, roi_crop_margins=None, default_roi_crop_margins=10, roi_crop_about_centre=None, default_roi_crop_about_centre=False, roi_pfiles=None, crop_to_match_size2=True, voxel_size2=None, default_roi_bands=None, roi_bands=None, pfiles2=None, most_points2=True, capture_output=False, keep_tmp_dir=False, metrics=None, default_slice_stats=None, default_by_slice=None, write_archive=True, im1_margins=None, im2_margins=None, margins_units='mm')
Constructor of Data class, allowing initialisation of an arbitrary set of attributes.
Parameters:
- adjust_reg_files(strategies=None, step=None, roi_names=None, params_by_reg_step=None)
- get_auto_steps()
- get_comparison(id1=None, id2=None, to_keep=None, strategies=None, steps=None, reg_steps=None, force=False, metrics=None, slice_stats=None, default_by_slice=None, voxel_size=None, name_as_index=False, **kwargs)
- get_comparison_steps(steps)
- get_reg_steps(step=None)
- get_registration(strategy=None, step=None, roi_name=None, force=False)
- get_segmentation(strategy=None, step=None, reg_step=None, force=False)
- segment(strategy=None, step=None, force=False, reg_setup_only=False)
- segment_roi(roi, strategy, step, most_points=True)
- segment_structure_set(ss, strategy, step, most_points=True)
- skrt.segmentation.ensure_dict(in_val, ensure_type=None)
Try to return a dictionary based on given input.
Parameters:
- in_val: dict/list
Data from which to construct returned dictionary. If <in_val> is a dictionary, its keys and values are used as the keys and values of the returned dictionary. If <in_val> is a list, list indices are used as keys in the returned dictionary, with corresponding list elements used as values. In both cases, <ensure_type> may be defined to ensure the type of values.
- ensure_type: function, default=None
Function applied to ensure the type of values in the returned dictionary. Possible functions include:
skrt.segmentation.ensure_image()
skrt.segmentation.ensure_structure_set()
If None, all types are accepted.
- skrt.segmentation.ensure_image(im)
Try to return an Image based on given input.
Parameter:
- im: str/array/nibabel.nifti1.Nifti1Image/skrt.image.Image, default=None
Source from which to create an Image instance. If None, return None. For information on Image sources, see documentation for skrt.image.Image.
- skrt.segmentation.ensure_structure_set(ss)
Try to return a StructureSet based on given input.
Parameter:
- image: str/list/skrt.structures.StructureSet, default=None
Source from which to create a StructureSet instance. If None, return None. For information on StructureSet sources, see documentation for skrt.structures.StructureSet.
- skrt.segmentation.get_atlases(paths, subtypes=None, subdirs=None, roi_names=None, structure_set_index=None, unsorted_dicom=True, max_atlas=None)
Obtain dictionary of atlas tuples (structure set and associated image).
By default, all structure sets in each dataset are considered, in reverse order of timestamp, and the first structure set with an associated image is accepted. It’s possible to consider only a specified structure set, or only structure sets that include specified ROIs.
In the dictionary returned, keys are identifiers, and values are tuples of the form (skrt.image.Image, skrt.structures.StructureSet).
Parameters:
- paths: str/pathlib.Path/list
Path, or list of paths, to patient datasets to be considered as atlases.
- subtypes:
String, or list of strings, identifying subtype(s) of imaging modality, for example “ct”, “mr”, “us”, to be considered as atlases. If None, all imaging modalities are considered.
- subdirsstr/list, default=None
Subdirectory, or list of subdirectories, grouping studies. If specified, only studies in this subdirectory, or in these subdirectories, are considered. Disregarded if unsorted_dicom is True.
- structure_set_index: int, default=None
Index, across all studies, of the structure set to be considered. If None, each structure set is considered, in reverse order of timestamp. Setting the index to be different from None can be useful if, for example, only the earliest structure set (index 0), or only the most-recent structure set (index -1), should be considered.
- unsorted_dicom: bool, default=True
If False, assume that data in a patient dataset are organised according to the VoxTox model. If True, don’t assume any particular organisation, and create data hierarchy based on information read from DICOM files.
- max_atlas: int, default=None
Maximum number of atlases to be returned. If None, there is no maximum.
- skrt.segmentation.get_contour_propagation_strategies(engine=None, engine_dir=None)
Return list of contour propagation strategies for registration engine.
- engine: str, default=None
String identifying registration engine, corresponding to a key of the dictionary skrt.registration.engines.
- engine_dir: pathlib.Path/str, default=None
Path to directory containing registration-engine software. It’s assumed that the registration engine is a key of the dictionary skrt.registration.engines, that the directory path includes this key, and that directory path doesn’t include any other keys of skrt.registration.engines.
.
- skrt.segmentation.get_fixed_and_moving(im1, im2, strategy)
Order target and atlas images as fixed and moving, depending on strategy.
For “push” strategy (ROI masks pulled from moving image), the target image is fixed and the atlas image is moving.
For “pull” strategy (ROI contours pushed to moving image), the atlas image is fixed and the target image is moving.
Parameters:
- im1: skrt.image.Image
Target image.
- im2: skrt.image.Image
Atlas image.
- strategy: str
Strategy to be used in contour propagation - one of “pull”, “push”.
- skrt.segmentation.get_option(opt=None, fallback_opt=None, allowed_opts=None)
Apply logic for selecting an allowed option.
Parameters:
- opt: int/bool/other/None, default=None
Specification of option: - if an element of <allowed_opts>, <opt> is returned; - if an integer, element <opt> of <allowed_opts> is returned; - if False, an empty string is returned; - if neither <opt> nor <fallback_opt> is an element of <allowed_opts>,
an integer, or False, then element -1 of <allowed_opts> is returned.
- fallback_opt: int/bool/other/None, default=None
Alternative specification of option. Considered in the same way as <opt>, if the latter isn’t an element of <allowed_opts>, an integer, or False.
- allowed_opts: list, default=None
List of allowed options.
- skrt.segmentation.get_options(opts=None, fallback_opts=None, allowed_opts=None)
Apply logic for selecting a list of allowed options.
Parameters:
- opts: int/bool/other/None/list, default=None
Specification of options: - if an element of <allowed_opts>, [<opt>] is returned; - if an integer, a list containing element <opt> of <allowed_opts>
is returned;
if False, an empty list is returned;
if True, <allowed_opts> is returned;
if a non-empty list, a list containing the values obtained by calling get_options for each input element is returned;
if <opts> isn’t an element of <allowed_opts>, an integer, False, True, or a non-empty list, and <fallback_opts> is None, then a list containing element -1 of <allowed_opts> is returned.
- fallback_opts: int/bool/other/None/list, default=None
Alternative specification of options. Considered in the same way as <opts>, if the latter isn’t an element of <allowed_opts>, an integer, False, True, or a non-empty list.
- allowed_opts: list, default=None
List of allowed options.
- skrt.segmentation.get_segmentation_steps()
Return list of segmentation steps.
- skrt.segmentation.get_segmentation_strategies()
Return list of segmentation strategies.
- skrt.segmentation.get_steps(step)
Get list of segmentation steps to run, up to and including <step>.
Parameter:
- step: str/int/list/None
Specification of segmentation step(s) to be run: - if None, all steps are to be run; - if a string or integer, the corresponding step is to be run; - if a list, all listed steps are to be run.
- skrt.segmentation.get_strategy(strategy=None, fallback_strategy=None, engine=None, engine_dir=None)
Apply logic for selecting an allowed strategy for contour propagation.
Parameters:
- strategystr/other, default=None
First choice strategy for contour propagation. If a string identifying a strategy supported by the registration engine used, <strategy> is returned. If any other string, an exception is raised. If not a string, <fallback_strategy> is considered.
- fallback_strategystr, default=None
Fallback strategy for contour propagation, considered if <strategy> isn’t a string. In this case: - if a string identifying a strategy supported by the
registration engine used, <fallback_strategy> is returned;
if an integer, element <fallback_strategy> of the list of strategies returned by skrt.segmentation.get_contour_propagation_strategies() is returned;
otherwise, element -1 of the list of strategies returned by skrt.segmentation.get_contour_propagation_strategies() is returned.
- engine: str, default=None
String identifying registration engine, corresponding to a key of the dictionary skrt.registration.engines.
- engine_dir: pathlib.Path/str, default=None
Path to directory containing registration-engine software. It’s assumed that the registration engine is a key of the dictionary skrt.registration.engines, that the directory path includes this key, and that directory path doesn’t include any other keys of skrt.registration.engines.
- skrt.segmentation.get_structure_set_index(ss_index, im)
Get positive index identifying structure set associated with an image.
If a structure set corresponding to the input index isn’t found, None is returned.
Parameters:
- ss_indexint
Positive or negative index identifying structure set in the list of structure sets associated with an image.
- imskrt.image.Image
Image for which positive index identifying associated structure set is to be returned.
- skrt.segmentation.load_mas(workdir='segmentation_workdir')
Load MultiAtlasSegmentation instance from work directory.
Parameter:
- workdir: str/pathlib.Path
Path to work directory for running multi-atlas segmentation. If the work directory was used by a previous MultiAtlasSegmentation instance, the data relating to this previous instance will be loaded. Otherwise, a MultiAtlasSegmentation instance will be loaded with default parameter settings.
- skrt.segmentation.load_sas(workdir='segmentation_workdir')
Load SingleAtlasSegmentation instance from work directory.
Parameter:
- workdir: str/pathlib.Path
Path to work directory for running single-atlas segmentation. If the work directory was used by a previous SingleAtlasSegmentation instance, the data relating to this previous instance will be loaded. Otherwise, a SingleAtlasSegmentation instance will be loaded with default parameter settings.
- skrt.segmentation.select_atlases(atlases, target=None, n_atlas=None, exclude_ids=None, selection=None, high_to_low=True, alignment=None, **kwargs)
Select atlases to register against target.
Parameters: atlases: dict
Dictionary of atlas tuples (structure set and associated image), such as returned by skrt.segmentation.get_atlases().
- target: skrt.image.Image, default=None
Image against which to register. When selection ordering isn’t based on a comparison metric, this can be None.
- n_atlas: int, default=None
Number of atlases to select, from those given as input. If None, all input atlases are returned, ordered according to selection.
- exclude_ids: list, default=None
List of atlas identifiers to be excluded from selection. This may be used, for example, if the target image is also an atlas, and self-registration isn’t wanted. If None, no atlases are excluded.
- selection: str/None, default=None
Ordering to be performed prior to selecting the first <n_atlas> atlases:
None: the input order is retained;
“random”: atlases are ordered randomly;
“sorted”: atlases are sorted in alphabetic order of identifier;
“reverse_sorted”: atlases are sorted in reverse alphabetic order of identifier;
image-comparison metric: atlases are compared with the target, and are ordered according to the specified image-comparison metric. Possibilities include “mutual-information”, “information quality ratio”, “fidelity” For a list of available metrics, see documentation for skrt.image.Image.get_comparison().
foreground-comparison metric: atlas foregrounds are compared with the target foreground and are ordered according to the specified foreground-comparison metric. Possibilities include “dice”, “centroid”, “volume_ratio”. For a list of available metrics, see documentation for skrt.structures.ROI.get_comparison().
- high_to_low: bool, default=True
When ordering for selection is based on a comparison metric, the ordering is from high to low if high_to_low is True, or otherwise is from low to high.
- alignment: tuple/dict/str, default=None
Strategy to be used for aligning atlases and target when comparing them. For strategy details, see documentation of skrt.image.get_alignment_translation(). The value set is passed to skrt.image.match_images_for_comparison(), to match atlas and target prior to evaluation of a comparison metric. Disregarded when ordering for selection isn’t based on a comparison metric.
- kwargs: dict
Keyword arguments passed to comparison methods: skrt.image.get_comparison() or skrt.image.get_foreground_comparison(), depending on selection specified.