GreedyFHist Python API

Registration

Segmentation

Options

This module contains all the options classes for configuring the registration.

class greedyfhist.options.options.AffineGreedyOptions(dim: int = 2, resolution: tuple[int, int] = <factory>, preprocessing_options: ~greedyfhist.options.options.PreprocessingOptions = <factory>, kernel_size: int = 10, cost_function: str = 'ncc', rigid_iterations: int | str = 10000, ia: str = 'ia-com-init', iteration_pyramid: list[int] = <factory>, n_threads: int = 1, keep_affine_transform_unbounded: bool = True, dof: int = 12)[source]

Commandline options parsed to Greedy.

More detailed information can be found in Greedy’s documentation. Some options are extended/overwritten.

dim

int Should always be set to 2.

Type:

int

resolution

Tuple[int, int] Image resolution after downscaling for Greedy.

Type:

tuple[int, int]

preprocessing_options

PreprocessingOptions Options for preprocessing.

Type:

greedyfhist.options.options.PreprocessingOptions

kernel_size

int kernel size for ‘ncc’ kernel metric.

Type:

int

cost_function

str cost function used to optimize the registration. Should always be set to ‘ncc’.

Type:

str

rigid_iterations

Union[int, str] Number of rigid iterations during initial registration of affine registration. If set to ‘auto’, the number of iterations for rigid matching is computed relative to the size of the offset from the center-of-mass initialization. Otherwise, uses the provided number.

Type:

int | str

ia

str Initial image alignment. ‘ia-com-init’ is a custom option for using the center-of-mass of image masks. Other options can be taken from Greedy.

Type:

str

iteration_pyramid

List[int] Iterations in the multiresolution pyramid.

Type:

list[int]

n_threads

int Number of threads. Defaults to 1, but 8 has shown the fastest registrations.

Type:

int

keep_affine_transform_unbounded

bool = True If true, keeps affine transform unbounded. Otherwise, affine transform is translated into a displacement field. Should be set to True.

Type:

bool

dof

int = 12 Degrees of freedom for registration. (6 = rigid, 12 = affine)

Type:

int

static default_options() AffineGreedyOptions[source]

Returns default options.

Return type:

AffineGreedyOptions

parse_dict(args_dict: dict)[source]

Function made to automatically parse attributes from dictionary.

Parameters:

args_dict (Dict)

to_dict() dict[source]

Return options as dictionary.

Return type:

Dict

class greedyfhist.options.options.NonrigidGreedyOptions(dim: int = 2, resolution: tuple[int, int] = <factory>, preprocessing_options: ~greedyfhist.options.options.PreprocessingOptions = <factory>, s1: float = 5, s2: float = 4, kernel_size: int = 10, cost_function: str = 'ncc', ia: str = 'ia-com-init', iteration_pyramid: list[int] = <factory>, n_threads: int = 1, use_sv: bool = False, use_svlb: bool = False, exp: int | None = None, use_gm_trim: bool = True, tscale: str | None = None)[source]

Commandline options parsed to Greedy.

More detailed information can be found in Greedy’s documentation. Some options are extended/overwritten.

dim

int Should always be set to 2.

Type:

int

resolution

Tuple[int, int] Image resolution after downscaling for Greedy.

Type:

tuple[int, int]

preprocessing_options

PreprocessingOptions Options for preprocessing.

Type:

greedyfhist.options.options.PreprocessingOptions

s1

float pre sigma value for nonrigid registration.

Type:

float

s2

float post sigma value for nonrigid registration.

Type:

float

kernel_size

int kernel size for ‘ncc’ kernel metric.

Type:

int

cost_function

str cost function used to optimize the registration. Should always be set to ‘ncc’.

Type:

str

ia

str Initial image alignment. ‘ia-com-init’ is a custom option for using the center-of-mass of image masks. Other options can be taken from Greedy.

Type:

str

iteration_pyramid

List[int] Iterations in the multiresolution pyramid.

Type:

list[int]

n_threads

int Number of threads. Defaults to 1, but 8 has shown the fastest registrations.

Type:

int

use_sv

bool Additional greedy option for nonrigid registration.

Type:

bool

use_svlb

bool Additional experimental greedy option for nonrigid registration.

Type:

bool

exp

Optional[int] Additional value used in conjunction with use_svlb.

Type:

int | None

use_gm_trim

bool = True Passes the gm_trim param to greedy.

Type:

bool

tscale

str | None = None If not None, passes tscale to greedy.

Type:

str | None

static default_nrpt_options() NonrigidGreedyOptions[source]

Returns suitable default options for nrpt registration.

Return type:

NonrigidGreedyOptions

static default_options() NonrigidGreedyOptions[source]

Returns default options.

Return type:

GreedyOptions

parse_dict(args_dict: dict)[source]

Function made to automatically parse attributes from dictionary.

Parameters:

args_dict (Dict)

to_dict() dict[source]

Return options as dictionary.

Return type:

Dict

class greedyfhist.options.options.PreprocessingOptions(moving_sr: int = 30, moving_sp: int = 25, fixed_sr: int = 30, fixed_sp: int = 25, enable_denoising: bool = True, disable_denoising_moving: bool = False, disable_denoising_fixed: bool = False)[source]

Contains all the options that can be used to register a moving to a fixed image.

moving_sr: int = 30

Color window radius for mean shift filtering in moving image.

moving_sp: int = 25

Pixel window readius for mean shift filtering in moving image.

fixed_sr: int = 30

Color window radius for mean shift filtering in fixed image.

fixed_sp: int = 25

Pixel window radius for mean shift filtering in fixed image.

enable_denoising: bool = True

Toggle for enabling denoising.

disable_denoising_moving: bool = False

Can be used to disable denoising in moving image.

disable_denoising_fixed: bool = False

Can be used to disable denoising in fixed image.

static default_options_nr() PreprocessingOptions[source]

Default options for nonrigid registration.

Return type:

PreprocessingOptions

parse_dict(args_dict: dict)[source]

Function made to automatically parse attributes from dictionary.

Parameters:

args_dict (Dict)

class greedyfhist.options.options.RegistrationOptions(path_to_greedy: str | None = None, segmentation: ~greedyfhist.options.segmentation_options.SegmentationOptions | ~typing.Callable[[~numpy.ndarray], ~numpy.ndarray] | str = <factory>, use_docker_container: bool = False, affine_registration_options: ~greedyfhist.options.options.AffineGreedyOptions = <factory>, nonrigid_registration_options: ~greedyfhist.options.options.NonrigidGreedyOptions = <factory>, pre_sampling_factor: float | str = 'auto', pre_sampling_max_img_size: int | None = 2000, do_affine_registration: bool = True, do_nonrigid_registration: bool = True, compute_reverse_nonrigid_registration: bool = False, temporary_directory: str = 'tmp', remove_temporary_directory: bool = True, disable_mask_generation: bool = False, tiling_options: ~greedyfhist.options.options.TilingOptions = <factory>, grp_n_proc: int | None = None)[source]

Contains all the options that can be used to register a moving to a fixed image.

path_to_greedy: str | None = None

Path to greedy executable. Only needed in the functional interface. In the object-oriented interface this property is set to GreedyFHist.path_to_greedy if necessary.

segmentation: SegmentationOptions | Callable[[numpy.ndarray], numpy.ndarray] | str | None

Handles segmentation accordingly: SegmentationOptions:

Contains configuration for YOLO8 based segmentations.

Callable:

Excepts a segmentation function that takes an input image and returns a mask where 1 denotes tissue area and 0 denotes background.

str:

One of ‘yolo-seg’, ‘entropy-based-seg’, ‘lum-area-seg’. If ‘yolo-seg’, the function load_yolo_segmentation is called to init a segmentation function based on the yolo model.

If ‘entropy-based-seg’, the function load_tissue_entropy_detection is called with default parameters and predict_tissue_from_entropy function is loaded.

If ‘lum-area-seg’, the function load_tissue_luminosity_area_detection is called with default values and predict_tissue_from_luminosity_and_area function is loaded.

None:

Loads yolo based segmentation with default options.

Either an options object containing configuration parameters for the standard tissue segmentation or a segmentation function that takes an image an input and returns a mask.

use_docker_container: bool = False

If the greedy executable is called through a docker image, set this to True and set path_to_greedy to the name of the docker container with the greedy executable.

affine_registration_options: AffineRegistrationOptions

Options for preprocessing and calling Greedy with affine registration otions.

nonrigid_registration_options: NonrigidRegistrationOptions

Options for preprocessing and calling Greedy with nonrigid registration options.

pre_sampling_factor: Union[float, str] = ‘auto’

Sampling factor prior to preprocessing. Does not affect registration accuracy, but can help to speed up the preprocessing considerable, especially for large images. If the factor is a float it is interpreted as a scaling factor that is applied on both images prior to preprocessing. If ‘auto’, then the pre_sampling_max_img_size is used to scale both images to have a maximum resolution of that factor.

pre_sampling_max_img_size: Optional[int] = 2000

Resizes moving and fixed image such that the largest axis of both images is set to a maximum of pre_sampling_resize_factor. This option is used if pre_sampling_factor is set to auto.

do_affine_registration: bool = True

Whether an affine registration is performed or not.

do_nonrigid_registration: bool = True

Whether a deformable registration is performed or not.

do_nrpt_registration: bool = False

If True, will perform nonrigid-pyramidic tiling registration. Will automatically set do_affine_registration to False and use nonrigid_registration_options for registration of tiles.

compute_reverse_nonrigid_registration: bool = False

Compute the reverse nonrigid registration. If do_affine_registration is True, uses the inverse of affine transformation as an initialization, if affine registration is used. This options is typically used for groupwise registration if the reverse transform is needed as well.

keep_affine_transform_unbounded: bool = True

If true, keeps affine transform unbounded. Otherwise, affine transform is translated into a displacement field. Should be set to True.

temporary_directory: str = ‘tmp’

Temporary directory used for storing Greedy in- and output.

remove_temporary_directory: bool = True

Sets whether the temporary directory is removed after registration.

disable_mask_generation: bool = False

If True, does not generation masks. Internally, the whole image area is declared as a mask. Does nothing if masks are provided.

tiling_options: TilingOptions

Options for defining tiling options in nrpt registration.

grp_n_proc: int | None = None

Number of concurrent processes used during groupwise registration. If None, performs every registration sequentially.

static affine_only_options() RegistrationOptions[source]

Default options for affine registration only.

Return type:

Registration Options

static default_options() RegistrationOptions[source]

Get default registration options.

Return type:

RegistrationOptions

static nonrigid_only_options() RegistrationOptions[source]

Default options for nonrigid registration only.

Return type:

RegistrationOptions

static nrpt_only_options() RegistrationOptions[source]

Default options for nrpt registration only.

Return type:

RegistrationOptions

static parse_cmdln_dict(args_dict: dict) RegistrationOptions[source]

Sets all values in dictionary that have a matching key in class’s __annotation__ field. key/value pairs for GreedyOpts are put in a sub dict, called ‘greedy’. ‘resolution’ is in string, e.g. ‘1024x1024’.

Parameters:

args_dict (Dict)

Return type:

RegistrationOptions

class greedyfhist.options.options.TilingOptions(enable_tiling: bool = False, tiling_mode: str = 'simple', stop_condition_tile_resolution: bool = False, stop_condition_pyramid_counter: bool = True, max_pyramid_depth: int | None = 0, pyramid_resolutions: list[int] | None = None, pyramid_tiles_per_axis: list[int] | None = None, tile_overlap: list[float] | float = 0.75, tile_size: int | tuple[int, int] = 1024, min_overlap: float = 0.1, n_procs: int | None = None)[source]

Options for performing nonrigid tiling registration.

enable_tiling

bool = False Enables tiling. If False, standard non-rigid registration is used.

Type:

bool

tiling_mode

str = ‘simple’ Tiling mode. Can either be ‘simple’ or ‘pyramid’.

Type:

str

stop_condition_tile_resolution

bool = False Relevant for pyramid tiling. One condition for stopping pyramid. If the size of a tile (without overlapping) if smaller than the downscaling resolution during registration, the pyramid is stopped. Ignored if tiling_mode==’simple’.

Type:

bool

stop_condition_pyramid_counter

bool = True Relevant for pyramid tiling. One condition for stopping pyramid. Stops as soon as the pyramid depth reaches max_pyramid_depth. Ignored if tiling_mode==’simple’.

Type:

bool

max_pyramid_depth

int | None = 0 Relevant for pyramid tiling. Defines stop condition for stop_condition_pyramid_counter.

Type:

int | None

pyramid_resolutions

list[int] | None = None Relevant for pyramid tiling. Defines the resolution of the tiles at each step of the pyramid.

Type:

list[int] | None

pyramid_tiles_per_axis

list[int] | None = None Relevant for pyramid tiling. Defines how many tiles are generated per axis. The number of tiles is then always the number of tiles on the x-axis * number of tiles on the y-axis.

Type:

list[int] | None

tile_overlap

list[float] | float = 0.75 Relevant for pyramid tiling. Gives the overlap of two neighboring tiles.

Type:

list[float] | float

tiles_size

int | tuple[int, int] = 1024 Relevant for simple tiling. Size of each tile extracted.

min_overlap

float = 0.1 Relevant for simple tiling. Minimum overlap between two neighboring tiles. Might be larger depending of how tiles fit into the images resolution. Last tile is likely to be affected if the tiles can not be evenly extracted from the image.

Type:

float

n_procs

int | None = None Number of concurrent processes for tile registration. If None, tiles are registered sequentially.

Type:

int | None

static default_options() TilingOptions[source]

Returns default options.

Return type:

TilingOptions

Utils

image

io

metrics

greedyfhist.utils.metrics.compute_distance_for_lm(warped_df: DataFrame, fixed_df: DataFrame) DataFrame[source]

Compute target registration error for each pair of matching landmarks. Lansmarks are matched with the ‘label’ column.

Parameters:
  • warped_df (pandas.DataFrame)

  • fixed_df (pandas.DataFrame)

Return type:

pandas.DataFrame

greedyfhist.utils.metrics.compute_tre(target_landmarks: DataFrame, warped_landmarks: DataFrame, target_shape: tuple[int, int]) tuple[float, float, float, float][source]
Computes target registration error based metrics:
  • mean relative target registration error

  • median relative target registration error

  • mean target registration error

  • median target registration error

Parameters:
  • target_landmarks (pandas.DataFrame)

  • warped_landmarks (pandas.DataFrame)

  • target_shape (tuple[int, int]) – Shape of target image. Used for computing relative target registration error.

Returns:

mean_rTRE, median_rTRE, mean_TRE, median_TRE

Return type:

tuple[float, float, float, float]

greedyfhist.utils.metrics.eucl(src: ndarray, dst: ndarray) float[source]

Computes euclidean distance between src and dst array.

Parameters:
  • src (numpy.ndarray)

  • dst (numpy.ndarray)

Return type:

float

tiling

class greedyfhist.utils.tiling.ImageTile(image: ndarray | Image, x_props: tuple[int, int, int, int, int, int], y_props: tuple[int, int, int, int, int, int], original_shape: tuple[int, int] | None = None)[source]

ImageTile class that contains an image tile and indices that were used to extract the tile and that are necessary to locate the image tile in its original source image.

image

Image tile

Type:

numpy.ndarray | SimpleITK.Image

x_props

Tiling information on x-axis.

Type:

tuple[int, int, int, int, int, int]

y_props

Tiling information on y-axis.

Type:

tuple[int, int, int, int, int, int]

original_shape

Original image resolution

Type:

tuple[int, int]

greedyfhist.utils.tiling.extract_image_tiles(img: ndarray, x_props: tuple[int, int, int, int, int, int], y_props: tuple[int, int, int, int, int, int]) list[ImageTile][source]

Extracts image tile using tiling indices for x and y axes.

Parameters:
  • img (numpy.ndarray) – Image to be tiled.

  • x_props (tuple[int, int, int, int, int, int]) – Tiling information in x-axis.

  • y_props (tuple[int, int, int, int, int, int]) – Tiling information in y-axis.

Returns:

List of image tiles.

Return type:

list[ImageTile]

greedyfhist.utils.tiling.get_tile_params(size: int, n_tiles: int = 2, overlap: float = 0.1) tuple[ndarray, ndarray, ndarray, ndarray, ndarray, ndarray][source]

Gets indices for tiling in one dimension. Indices include start index in image, start index in image with overlap, start index in tile (considering overlap), end index in image, end index in image with overlap, end index in tile.

Parameters:
  • size (int) – size of dimension

  • n_tiles (int, optional) – Number of tiles to return. Defaults to 2.

  • overlap (float, optional) – Overlap between tiles in percent. Defaults to 0.1.

Returns:

Start and end indices for tiling.

Return type:

tuple[int, int, int, int, int, int]

greedyfhist.utils.tiling.reassemble_np(image_tiles: list[ImageTile], outputshape: tuple[int, int] | tuple[int, int, int]) ndarray[source]

Reassembles image as numpy.ndarray tiles to an image.

Parameters:
  • image_tiles (list[ImageTile]) – Tiles to reassemble.

  • outputshape (tuple[int, int] | tuple[int, int, int]) – Shape of the output image that is reassembled.

Returns:

Reassembled image.

Return type:

numpy.ndarray

greedyfhist.utils.tiling.reassemble_sitk_displacement_field(image_tiles: list[ImageTile], outputshape: tuple[int, int] | tuple[int, int, int]) ndarray[source]

Reassembles tile-wise displacement fields into a whole image displacement field.

Parameters:
  • image_tiles (list[&#39;ImageTile&#39;]) – _description_

  • outputshape (tuple[int, int] | tuple[int, int, int]) – _description_

Returns:

Displacement field as numpy.ndarray.

Return type:

numpy.ndarray

greedyfhist.utils.tiling.reassemble_sitk_displacement_field_from_tile_size(image_tiles: list[ImageTile], outputshape: tuple[int, int] | tuple[int, int, int]) ndarray[source]

Reassembles tile-wise displacement fields into a whole image displacement field.

Parameters:
  • image_tiles (list[&#39;ImageTile&#39;]) – _description_

  • outputshape (tuple[int, int] | tuple[int, int, int]) – _description_

Returns:

Displacement field as numpy.ndarray.

Return type:

numpy.ndarray

utils

General utils files. Lowest level of utils. Cannot import from anywhere else in the project.

greedyfhist.utils.utils.affine_registration(path_to_greedy: str, path_to_fixed_image: str, path_to_moving_image: str, path_output: str, offset: int, ia: str, options: AffineGreedyOptions, use_docker_container: bool = False, temp_directory: str = '') CompletedProcess[source]

Calls greedy’s affine registration function.

Parameters:
  • path_to_greedy (str) – _description_

  • path_to_fixed_image (str) – _description_

  • path_to_moving_image (str) – _description_

  • path_output (str) – _description_

  • offset (int) – _description_

  • ia (str) – _description_

  • options (GreedyOptions) – _description_

Returns:

Return of command line execution.

Return type:

_type_

greedyfhist.utils.utils.build_cmd_string(path_to_exec: str, args: dict[str, str | list[str]]) str[source]

Small custom function for collection arguments in a function call.

greedyfhist.utils.utils.call_command(cmd: str)[source]

Simple wrapper function around a command. :param cmd: :return:

greedyfhist.utils.utils.compose_inv_reg_transforms(transform: Transform, moving_preprocessing_params: dict, fixed_preprocessing_params: dict) Transform[source]

Pre- and appends preprocessing steps from moving and fixed image as transforms to backward affine/nonrigid registration.

Parameters:
  • transform (SimpleITK.SimpleITK.Transform) – Computed affine/nonrigid registration

  • internal_reg_params (InternalRegParams) – Contains parameters of preprocessing steps.

Returns:

Composited end-to-end transform.

Return type:

SimpleITK.SimpleITK.Transform

greedyfhist.utils.utils.compose_reg_transforms(transform: Transform, moving_preprocessing_params: dict, fixed_preprocessing_params: dict) Transform[source]

Pre- and appends preprocessing steps from moving and fixed image as transforms to forward affine/nonrigid registration.

Parameters:
  • transform (SimpleITK.SimpleITK.Transform) – Computed affine/nonrigid registration

  • internal_reg_params (InternalRegParams) – Contains parameters of preprocessing steps.

  • reverse (bool) – Switches moving and fixed preprocessing params if True.

Returns:

Composited end-to-end registration.

Return type:

SimpleITK.SimpleITK.Transform

greedyfhist.utils.utils.composite_sitk_transforms(transforms: list[Transform]) Transform[source]

Composites all Transforms into one composite transform.

Parameters:

transforms (List[SimpleITK.SimpleITK.Transform])

Return type:

SimpleITK.SimpleITK.Transform

greedyfhist.utils.utils.composite_warps(path_to_greedy: str, path_small_affine: str | None, path_small_warp: str | None, path_small_ref_img: str, path_small_composite_warp: str, invert=False) CompletedProcess[source]

Calls greedy to composite transformations.

Parameters:
  • path_to_greedy (str)

  • path_small_affine (str | None) – Path to affine transform.

  • path_small_warp (str | None) – Path to displacement field.

  • path_small_ref_img (str) – Path to reference image.

  • path_small_composite_warp (str) – Path to output composite displacement field.

  • invert (bool, optional) – If True, inverts to order of composition. Defaults to False.

Return type:

subprocess.CompletedProcess

greedyfhist.utils.utils.correct_img_dtype(img: ndarray) ndarray[source]

Changes the image type from float to np.uint8 if necessary.

Parameters:

img (numpy.ndarray)

Return type:

numpy.ndarray

greedyfhist.utils.utils.deformable_registration(path_to_greedy: str, path_fixed_image: str, path_moving_image: str, options: NonrigidGreedyOptions, output_warp: str | None = None, output_inv_warp: str | None = None, affine_pre_transform: str | None = None, ia: tuple[str, str] | None = None, use_docker_container: bool = False, temp_directory: str = '') CompletedProcess[source]

Calls the deformable registration command of greedy.

Parameters:
  • path_to_greedy (str)

  • path_fixed_image (str)

  • path_moving_image (str)

  • options (GreedyOptions) – Contains options to pass to greedy.

  • output_warp (str, optional) – Defaults to None.

  • output_inv_warp (str, optional) – Defaults to None.

  • affine_pre_transform (_type_, optional) – Contains path to affine_pre_transform. Necessary if ia is ia-com-init. Defaults to None.

Returns:

Return of command line execution.

Return type:

subprocess.CompletedProcess

greedyfhist.utils.utils.derive_sampling_factors(pre_sampling_factor: float | str, max_size: int, pre_sampling_max_img_size: int | None) tuple[float, float][source]

Derives resampling factor for registration.

Parameters:
  • pre_sampling_factor (float | str)

  • max_size (int)

  • pre_sampling_max_img_size (int | None)

Return type:

tuple[float, float]