PartSegCore base

On this page there are described base classes of PartSegCore module

.algorithm_describe_base

class PartSegCore.algorithm_describe_base.AddRegisterMeta(name, bases, attrs, **kwargs)[source]
class PartSegCore.algorithm_describe_base.AlgorithmDescribeBase[source]

This is abstract class for all algorithm exported to user interface. Based on get_name and get_fields methods the interface will be generated For each group of algorithm base abstract class will add additional methods

classmethod get_fields()[source]

This function return list of parameters needed by algorithm. It is used for generate form in User Interface

Return type

List[Union[AlgorithmProperty, str]]

Returns

list of algorithm parameters and comments

abstract classmethod get_name()[source]

Algorithm name. It will be used during interface generating and in registering to proper PartSeg.PartSegCore.algorithm_describe_base.Register.

Return type

str

Returns

name of algorithm

class PartSegCore.algorithm_describe_base.AlgorithmDescribeBaseMeta(name, bases, attrs, **kwargs)[source]
exception PartSegCore.algorithm_describe_base.AlgorithmDescribeNotFound[source]

When algorithm description not found

class PartSegCore.algorithm_describe_base.AlgorithmProperty(name, user_name, default_value, options_range=None, possible_values=None, value_type=None, help_text='', per_dimension=False, mgi_options=None, **kwargs)[source]

This class is used to verbose describe algorithm parameters

Parameters
  • name (str) – name of parameter used in code

  • user_name (str) – name presented to user in interface

  • default_value (Union[str, int, float, object]) – initial value which be used during interface generation

  • help_text (str) – toll tip presented to user when keep mouse over widget

pydantic model PartSegCore.algorithm_describe_base.AlgorithmSelection[source]

Base class for algorithm selection. For given algorithm there should be Register instance set __register__ class variable.

Show JSON schema
{
   "title": "AlgorithmSelection",
   "description": "Base class for algorithm selection.\nFor given algorithm there should be Register instance set __register__ class variable.",
   "type": "object",
   "properties": {
      "name": {
         "title": "Name",
         "type": "string"
      },
      "values": {
         "title": "Values",
         "anyOf": [
            {
               "$ref": "#/definitions/BaseModel"
            },
            {
               "type": "object"
            }
         ]
      },
      "class_path": {
         "title": "Class Path",
         "default": "",
         "type": "string"
      }
   },
   "required": [
      "name",
      "values"
   ],
   "additionalProperties": false,
   "definitions": {
      "BaseModel": {
         "title": "BaseModel",
         "type": "object",
         "properties": {}
      }
   }
}

Config
  • extra: str = forbid

Fields
Validators
field class_path: str = ''
Validated by
field name: str [Required]
Validated by
field values: Union[pydantic.main.BaseModel, Dict[str, Any]] [Required]
Validated by
algorithm()[source]
validator check_name  »  name[source]
classmethod get_default()[source]
classmethod register(value, replace=False, old_names=None)[source]

Function for registering AlgorithmDescribeBase based algorithms :type value: TypeVar(AlgorithmType, bound= Type[AlgorithmDescribeBase]) :param value: algorithm to register :param replace: replace existing algorithm, be patient with :type old_names: Optional[List[str]] :param old_names: list of old names for registered class

Return type

TypeVar(AlgorithmType, bound= Type[AlgorithmDescribeBase])

validator update_class_path  »  class_path[source]
validator update_values  »  values[source]
pydantic model PartSegCore.algorithm_describe_base.ROIExtractionProfile[source]
Variables
  • ~.name (str) – name for segmentation profile

  • ~.algorithm (str) – Name of algorithm

  • ~.values (dict) – algorithm parameters

Show JSON schema
{
   "title": "ROIExtractionProfile",
   "description": ":ivar str ~.name: name for segmentation profile\n:ivar str ~.algorithm: Name of algorithm\n:ivar dict ~.values: algorithm parameters",
   "type": "object",
   "properties": {
      "name": {
         "title": "Name",
         "type": "string"
      },
      "algorithm": {
         "title": "Algorithm",
         "type": "string"
      },
      "values": {
         "title": "Values"
      }
   },
   "required": [
      "name",
      "algorithm"
   ],
   "additionalProperties": false
}

Config
  • extra: str = forbid

Fields
Validators
field algorithm: str [Required]
field name: str [Required]
field values: Any = None
Validated by
pretty_print(algorithm_dict)[source]
classmethod print_dict(dkt, indent=0, name='')[source]
Return type

str

validator validate_values  »  values[source]
class PartSegCore.algorithm_describe_base.ROIExtractionProfileMeta(name, bases, attrs, **kwargs)[source]
class PartSegCore.algorithm_describe_base.Register(*args, class_methods=None, methods=None, suggested_base_class=None, **kwargs)[source]

Dict used for register AlgorithmDescribeBase classes. All registers from PartSeg.PartSegCore.register are this :param class_methods: list of method which should be implemented as class method it will be checked during add as args or with Register.register() method :param methods: list of method which should be instance method

get_default()[source]

Calculate default algorithm name for given dict.

Return type

str

Returns

name of algorithm

register(value, replace=False, old_names=None)[source]

Function for registering AlgorithmDescribeBase based algorithms :type value: TypeVar(AlgorithmType, bound= Type[AlgorithmDescribeBase]) :param value: algorithm to register :type replace: bool :param replace: replace existing algorithm, be patient with :type old_names: Optional[List[str]] :param old_names: list of old names for registered class

values()[source]
Return type

Iterable[TypeVar(AlgorithmType, bound= Type[AlgorithmDescribeBase])]

PartSegCore.algorithm_describe_base.base_model_to_algorithm_property(obj)[source]

Convert pydantic model to list of AlgorithmPropert nad strings.

Parameters

obj (Type[BaseModel]) –

Return type

List[Union[AlgorithmProperty, str]]

Returns

.image_operations

class PartSegCore.image_operations.NoiseFilterType(value)[source]

Bases: enum.Enum

An enumeration.

class PartSegCore.image_operations.RadiusType(value)[source]

Bases: enum.Enum

If operation should be performed and if on each layer separately on globally

NO = 0

No operation

R2D = 1

operation in each layer separately

R3D = 2

operation on whole stack

PartSegCore.image_operations.apply_filter(filter_type, image, radius, layer=True)[source]

Apply operation selected by filter type to image.

Parameters
Returns

image after operation

Return type

np.ndarray

PartSegCore.image_operations.bilateral(image, radius, layer=True)[source]

Gaussian blur of image.

Parameters
  • image (np.ndarray) – image to apply gaussian filter

  • radius (float) – radius for gaussian kernel

  • layer (bool) – if operation should be run on each layer separately

Returns

PartSegCore.image_operations.dilate(image, radius, layer=True)[source]

Dilate of image.

Parameters
  • image – image to apply dilation

  • radius – dilation radius

  • layer – if operation should be run on each layer separately

Returns

PartSegCore.image_operations.erode(image, radius, layer=True)[source]

Erosion of image

Parameters
  • image – image to apply erosion

  • radius – erosion radius

  • layer – if operation should be run on each layer separately

Returns

PartSegCore.image_operations.gaussian(image, radius, layer=True)[source]

Gaussian blur of image.

Parameters
  • image (np.ndarray) – image to apply gaussian filter

  • radius (float) – radius for gaussian kernel

  • layer (bool) – if operation should be run on each layer separately

Returns

PartSegCore.image_operations.median(image, radius, layer=True)[source]

Median blur of image.

Parameters
  • image (np.ndarray) – image to apply median filter

  • radius (float) – radius for median kernel

  • layer (bool) – if operation should be run on each layer separately

Returns

PartSegCore.image_operations.to_binary_image(image)[source]

Convert image to binary. All positive values are set to 1.

.json_hooks

class PartSegCore.json_hooks.PartSegEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: local_migrator._serialize_hooks.Encoder

.io_utils

class PartSegCore.io_utils.LoadBase[source]

Bases: PartSegCore.algorithm_describe_base.AlgorithmDescribeBase, abc.ABC

classmethod get_fields()[source]

This function return list of parameters needed by algorithm. It is used for generate form in User Interface

Returns

list of algorithm parameters and comments

abstract classmethod load(load_locations, range_changed=None, step_changed=None, metadata=None)[source]

Function for load data

Parameters
  • load_locations (List[Union[str, BytesIO, Path]]) – list of files to load

  • range_changed (Optional[Callable[[int, int], Any]]) – callback function for inform about number of steps to be done

  • step_changed (Optional[Callable[[int], Any]]) – callback function for report that single step has been done

  • metadata (Optional[dict]) – additional information needed by function. Like default spacing for load image

Return type

Union[ProjectInfoBase, List[ProjectInfoBase]]

Returns

Project info or list of project info

classmethod number_of_files()[source]

Number of files required for load method

classmethod partial()[source]

Inform that this class load complete data

class PartSegCore.io_utils.LoadPlanExcel[source]

Bases: PartSegCore.io_utils.LoadBase

classmethod get_name()[source]

Algorithm name. It will be used during interface generating and in registering to proper PartSeg.PartSegCore.algorithm_describe_base.Register.

Return type

str

Returns

name of algorithm

classmethod load(load_locations, range_changed=None, step_changed=None, metadata=None)[source]

Function for load data

Parameters
  • load_locations (List[Union[str, BytesIO, Path]]) – list of files to load

  • range_changed (Optional[Callable[[int, int], Any]]) – callback function for inform about number of steps to be done

  • step_changed (Optional[Callable[[int], Any]]) – callback function for report that single step has been done

  • metadata (Optional[dict]) – additional information needed by function. Like default spacing for load image

Returns

Project info or list of project info

class PartSegCore.io_utils.LoadPlanJson[source]

Bases: PartSegCore.io_utils.LoadBase

classmethod get_name()[source]

Algorithm name. It will be used during interface generating and in registering to proper PartSeg.PartSegCore.algorithm_describe_base.Register.

Return type

str

Returns

name of algorithm

classmethod load(load_locations, range_changed=None, step_changed=None, metadata=None)[source]

Function for load data

Parameters
  • load_locations (List[Union[str, BytesIO, Path]]) – list of files to load

  • range_changed (Optional[Callable[[int, int], Any]]) – callback function for inform about number of steps to be done

  • step_changed (Optional[Callable[[int], Any]]) – callback function for report that single step has been done

  • metadata (Optional[dict]) – additional information needed by function. Like default spacing for load image

Returns

Project info or list of project info

class PartSegCore.io_utils.LoadPoints[source]

Bases: PartSegCore.io_utils.LoadBase

classmethod get_fields()[source]

This function return list of parameters needed by algorithm. It is used for generate form in User Interface

Return type

List[Union[AlgorithmProperty, str]]

Returns

list of algorithm parameters and comments

classmethod get_name()[source]

Algorithm name. It will be used during interface generating and in registering to proper PartSeg.PartSegCore.algorithm_describe_base.Register.

Return type

str

Returns

name of algorithm

classmethod load(load_locations, range_changed=None, step_changed=None, metadata=None)[source]

Function for load data

Parameters
  • load_locations (List[Union[str, BytesIO, Path]]) – list of files to load

  • range_changed (Optional[Callable[[int, int], Any]]) – callback function for inform about number of steps to be done

  • step_changed (Optional[Callable[[int], Any]]) – callback function for report that single step has been done

  • metadata (Optional[dict]) – additional information needed by function. Like default spacing for load image

Return type

PointsInfo

Returns

Project info or list of project info

classmethod partial()[source]

Inform that this class load complete data

exception PartSegCore.io_utils.NotSupportedImage[source]

Bases: Exception

class PartSegCore.io_utils.PointsInfo(file_path, points)[source]

Bases: NamedTuple

file_path: str

Alias for field number 0

points: numpy.ndarray

Alias for field number 1

class PartSegCore.io_utils.SaveBase[source]

Bases: PartSegCore.algorithm_describe_base.AlgorithmDescribeBase, abc.ABC

abstract classmethod save(save_location, project_info, parameters, range_changed=None, step_changed=None)[source]
Parameters
  • save_location (Union[str, BytesIO, Path]) – location to save, can be buffer

  • project_info – all project data

  • parameters (dict) – additional parameters for saving method

  • range_changed – report function for inform about steps num

  • step_changed – report function for progress

class PartSegCore.io_utils.SaveMaskAsTiff[source]

Bases: PartSegCore.io_utils.SaveBase

classmethod get_fields()[source]

This function return list of parameters needed by algorithm. It is used for generate form in User Interface

Returns

list of algorithm parameters and comments

classmethod get_name()[source]

Algorithm name. It will be used during interface generating and in registering to proper PartSeg.PartSegCore.algorithm_describe_base.Register.

Returns

name of algorithm

classmethod save(save_location, project_info, parameters, range_changed=None, step_changed=None)[source]
Parameters
  • save_location (Union[str, BytesIO, Path]) – location to save, can be buffer

  • project_info – all project data

  • parameters (dict) – additional parameters for saving method

  • range_changed – report function for inform about steps num

  • step_changed – report function for progress

class PartSegCore.io_utils.SaveROIAsNumpy[source]

Bases: PartSegCore.io_utils.SaveBase

classmethod get_fields()[source]

This function return list of parameters needed by algorithm. It is used for generate form in User Interface

Returns

list of algorithm parameters and comments

classmethod get_name()[source]

Algorithm name. It will be used during interface generating and in registering to proper PartSeg.PartSegCore.algorithm_describe_base.Register.

Returns

name of algorithm

classmethod save(save_location, project_info, parameters=None, range_changed=None, step_changed=None)[source]
Parameters
  • save_location (Union[str, BytesIO, Path]) – location to save, can be buffer

  • project_info – all project data

  • parameters (Optional[dict]) – additional parameters for saving method

  • range_changed – report function for inform about steps num

  • step_changed – report function for progress

class PartSegCore.io_utils.SaveROIAsTIFF[source]

Bases: PartSegCore.io_utils.SaveBase

classmethod get_fields()[source]

This function return list of parameters needed by algorithm. It is used for generate form in User Interface

Returns

list of algorithm parameters and comments

classmethod get_name()[source]

Algorithm name. It will be used during interface generating and in registering to proper PartSeg.PartSegCore.algorithm_describe_base.Register.

Returns

name of algorithm

classmethod save(save_location, project_info, parameters, range_changed=None, step_changed=None)[source]
Parameters
  • save_location (Union[str, BytesIO, Path]) – location to save, can be buffer

  • project_info – all project data

  • parameters (dict) – additional parameters for saving method

  • range_changed – report function for inform about steps num

  • step_changed – report function for progress

class PartSegCore.io_utils.SaveScreenshot[source]

Bases: PartSegCore.io_utils.SaveBase

classmethod get_fields()[source]

This function return list of parameters needed by algorithm. It is used for generate form in User Interface

Return type

List[Union[AlgorithmProperty, str]]

Returns

list of algorithm parameters and comments

classmethod get_name()[source]

Algorithm name. It will be used during interface generating and in registering to proper PartSeg.PartSegCore.algorithm_describe_base.Register.

Return type

str

Returns

name of algorithm

classmethod save(save_location, project_info, parameters, range_changed=None, step_changed=None)[source]
Parameters
  • save_location (Union[str, BytesIO, Path]) – location to save, can be buffer

  • project_info – all project data

  • parameters (dict) – additional parameters for saving method

  • range_changed – report function for inform about steps num

  • step_changed – report function for progress

class PartSegCore.io_utils.SegmentationType(value)[source]

Bases: enum.Enum

An enumeration.

exception PartSegCore.io_utils.WrongFileTypeException[source]

Bases: Exception

PartSegCore.io_utils.find_problematic_entries(data)[source]

Find top nodes with "__error__" key. If node found then its children is not checked.

Parameters

data (Any) – data to be checked

Return type

List[MutableMapping]

Returns

top level entries with “__error__” key

PartSegCore.io_utils.find_problematic_leafs(data)[source]

Find bottom nodes with "__error__" key. If any children has "__error__" then such node is not returned.

Parameters

data (Any) – data to be checked.

Return type

List[MutableMapping]

Returns

bottom level entries with “__error__” key

PartSegCore.io_utils.load_matadata_part(data)

Load serialized data. Get valid entries.

Parameters

data (Union[str, Path]) – path to file or string to be decoded.

Return type

Tuple[Any, List[Tuple[str, dict]]]

Returns

PartSegCore.io_utils.load_metadata_part(data)[source]

Load serialized data. Get valid entries.

Parameters

data (Union[str, Path]) – path to file or string to be decoded.

Return type

Tuple[Any, List[Tuple[str, dict]]]

Returns

PartSegCore.io_utils.open_tar_file(file_data, mode='r')[source]

Create tar file from path or buffer. If passed TarFile then return it.

Return type

Tuple[TarFile, str]

.mask_create

pydantic model PartSegCore.mask_create.MaskProperty[source]

Bases: PartSegCore.utils.BaseModel

Description of creation mask from segmentation

Variables
  • ~.dilate (RadiusType) – Select dilation mode.

  • ~.dilate_radius (int) – Radius of dilation calculate with respect of image spacing.

  • ~.fill_holes (RadiusType) – Select if fill holes and if it should be done in 2d or 3d.

  • ~.max_holes_size (int) – Maximum holes size if positive. Otherwise fill all holes.

  • ~.save_components (bool) – If mask should save components of segmentation or set to 1.

  • ~.clip_to_mask (bool) – If resulted should be clipped to previous mask (if exist). Useful for positive dilate radius

  • ~.reversed_mask (bool) – If mask should be reversed (region which are not part of segmentation)

Show JSON schema
{
   "title": "MaskProperty",
   "description": "Description of creation mask from segmentation\n\n:ivar RadiusType ~.dilate: Select dilation mode.\n:ivar int ~.dilate_radius: Radius of dilation calculate with respect of image spacing.\n:ivar RadiusType ~.fill_holes: Select if fill holes and if it should be done in 2d or 3d.\n:ivar int ~.max_holes_size: Maximum holes size if positive. Otherwise fill all holes.\n:ivar bool ~.save_components: If mask should save components of segmentation or set to 1.\n:ivar bool ~.clip_to_mask: If resulted should be clipped to previous mask (if exist).\n    Useful for positive dilate radius\n:ivar bool ~.reversed_mask: If mask should be reversed (region which are not part of segmentation)",
   "type": "object",
   "properties": {
      "dilate": {
         "$ref": "#/definitions/RadiusType"
      },
      "dilate_radius": {
         "title": "Dilate Radius",
         "type": "integer"
      },
      "fill_holes": {
         "$ref": "#/definitions/RadiusType"
      },
      "max_holes_size": {
         "title": "Max Holes Size",
         "type": "integer"
      },
      "save_components": {
         "title": "Save Components",
         "type": "boolean"
      },
      "clip_to_mask": {
         "title": "Clip To Mask",
         "type": "boolean"
      },
      "reversed_mask": {
         "title": "Reversed Mask",
         "default": false,
         "type": "boolean"
      }
   },
   "required": [
      "dilate",
      "dilate_radius",
      "fill_holes",
      "max_holes_size",
      "save_components",
      "clip_to_mask"
   ],
   "additionalProperties": false,
   "definitions": {
      "RadiusType": {
         "title": "RadiusType",
         "description": "If operation should be performed and if on each layer separately on globally",
         "enum": [
            0,
            1,
            2
         ]
      }
   }
}

Config
  • extra: str = forbid

Fields
field clip_to_mask: bool [Required]
field dilate: PartSegCore.image_operations.RadiusType [Required]
field dilate_radius: int [Required]
field fill_holes: PartSegCore.image_operations.RadiusType [Required]
field max_holes_size: int [Required]
field reversed_mask: bool = False
field save_components: bool [Required]
classmethod simple_mask()[source]

Create MaskProperty which describe simple conversion segmentation to mask

Return type

MaskProperty

PartSegCore.mask_create.calculate_mask(mask_description, roi, old_mask, spacing, components=None, time_axis=0)[source]

Function for calculate mask base on MaskProperty. If dilate_radius is negative then holes closing is done before erode, otherwise it is done after dilate

Parameters
  • mask_description (MaskProperty) – information how calculate mask

  • roi (np.ndarray) – array on which mask is calculated

  • old_mask (Optional[np.ndarray]) – if in mask_description there is set to crop and old_mask is not None then final mask is clipped to this area

  • spacing (Iterable[Union[float,int]]) – spacing of image. Needed for calculating radius of dilate

  • components (Optional[List[int]]) – If present inform which components should be used when calculation mask, otherwise use all.

  • time_axis (Optional[int]) – which axis of array should be treated as time. IF none then none.

Returns

new mask

Return type

np.ndarray

PartSegCore.mask_create.fill_2d_holes_in_mask(mask, volume)[source]

fill holes in each 2d layer separately

Parameters
  • mask (ndarray) – mask to fill holes

  • volume (int) – minimum volume

Return type

ndarray

Returns

modified mask

PartSegCore.mask_create.fill_holes_in_mask(mask, volume)[source]

Fil holes in mask. If volume has positive Value then fill holes only smaller than this value

Parameters
  • mask (ndarray) – mask to be modified

  • volume (int) – maximum volume of holes which will be filled

Return type

ndarray

Returns

modified mask

PartSegCore.mask_create.mp_eq(self, other)[source]

Compare two MaskProperty

.project_info

class PartSegCore.project_info.AdditionalLayerDescription(data, layer_type, name='')[source]

Bases: object

Dataclass

Variables
  • data (numpy.ndarray) – layer data

  • layer_type (str) – napari layer type

  • name (str) – layer name

exception PartSegCore.project_info.HistoryProblem[source]

Bases: Exception

class PartSegCore.project_info.ProjectInfoBase(*args, **kwargs)[source]

Bases: Protocol

This is base protocol for Project Information.

Variables
  • ~.file_path (str) – path to current preceded file

  • ~.image (Image) – project image

  • ~.segmentation (numpy.ndarray) – numpy array representing current project ROI

  • ~.roi_info (ROIInfo) – segmentation metadata

  • ~.mask (Optional[numpy.ndarray]) – mask used in project

  • ~.history (List[HistoryElement]) – history of calculation

  • errors (str) – information about problems with current project

get_raw_copy()[source]

Create copy with only image

PartSegCore.project_info.calculate_mask_from_project(mask_description, project, components=None)[source]

Function for calculate mask base on MaskProperty. This function calls calculate_mask() with arguments from project.

Parameters
  • mask_description (MaskProperty) – information how calculate mask

  • project (ProjectInfoBase) – project with information about segmentation

  • components (Optional[List[int]]) – If present inform which components should be used when calculation mask, otherwise use all.

Returns

new mask

Return type

np.ndarray

.register

This module is designed to provide more stable api for PartSeg plugins. All operations ar class based. If, in base object, some function is @classmethod, the it can be called without creating class instance. So also plugins need to satisfy it.

RegisterEnum: used as key in all other members. Elements are described in its docstring

base_class_dict: Dict in which information about base class for given operation is stored. The inheritance is not checked, but api must be implemented.

register: function for registering operation in inner structures.

register_dict: holds information where register given operation type. Strongly suggest to use register function instead.

class PartSegCore.register.RegisterEnum(value)[source]

Given types of operation are supported as plugins

analysis_algorithm = 3

algorithm for creating segmentation in analysis PartSeg part

analysis_load = 6

load functions for analysis part

analysis_measurement = 12

measurements algorithms (analysis mode)

analysis_save = 5

save functions for analysis part

flow = 0

algorithm for calculation flow from core object to borders. For spiting touching objects, deprecated

image_transform = 8

transform image, like interpolation

mask_algorithm = 4

algorithm for creating segmentation in mask PartSeg part

mask_load = 7

load functions for mask part

mask_save_components = 10

save each segmentation component in separate file. Save location is directory

mask_save_parameters = 9

save metadata for mask part (currently creating json file)

mask_save_segmentation = 11

save project (to one file) in mask part

noise_filtering = 2

filter noise from image

roi_analysis_segmentation_algorithm = 13

algorithm for creating segmentation in analysis PartSeg part

roi_mask_segmentation_algorithm = 14

algorithm for creating segmentation in mask PartSeg part

sprawl = 16

algorithm for calculation flow from core object to borders. For spiting touching objects, deprecated

threshold = 1

threshold algorithms. From greyscale array to binary array

PartSegCore.register.register(target, target_type, replace=False, old_names=None)[source]

Function for registering new operations in PartSeg inner structures.

Parameters
  • target (Type[AlgorithmDescribeBase]) – operation to register in PartSeg inner structures

  • target_type (RegisterEnum) – Which type of operation.

  • replace – force to replace operation if same name is defined. Dangerous.

PartSegCore.register.base_class_dict

dict with base class for given type of algorithm, keys are RegisterEnum members

.mask_partition_utils

This module contains some not fully intuitive algorithm for splitting masked area. They are designed for measurements, but should be also available as segmentation algorithm to allow user to preview, for better intuition how it works and which parameters are good for their purpose.

Better option is to implement this utils as class based with base class AlgorithmDescribeBase. Then do not need to manage algorithm parameters in places where it is used.

Both class from this module are designed for spherical mask, but may be useful als for others.

class PartSegCore.mask_partition_utils.BorderRim[source]

Bases: PartSegCore.algorithm_describe_base.AlgorithmDescribeBase

This class implement border rim (Annulus like) calculation. For given mask and image spacing it marks as 1 all pixels in given distance from mask border.

https://en.wikipedia.org/wiki/Annulus_(mathematics)

The algorithm is:

  1. For each image voxel calculate distance from background (0 labeled voxels in mask) with respect of voxel size

  2. Select these voxels which are closer than given distance.

This algorithm has following parameters:

  • distance (ConstrainedFloatValue)- Distance

  • units (Units)- Units

static border_mask(mask, distance, units, voxel_size, **_)[source]

This is function which implement calculation.

Parameters
  • mask (ndarray) – area for which rim should be calculated. 2d or 3d numpy array,

  • distance (float) – distance from border which will be marked.

  • units (Units) – in which unit distance is given

  • voxel_size – Image spacing in absolute units

  • _ – ignored arguments

Return type

Optional[ndarray]

Returns

border rim marked with 1

classmethod get_name()[source]

Algorithm name. It will be used during interface generating and in registering to proper PartSeg.PartSegCore.algorithm_describe_base.Register.

Return type

str

Returns

name of algorithm

class PartSegCore.mask_partition_utils.MaskDistanceSplit[source]

Bases: PartSegCore.algorithm_describe_base.AlgorithmDescribeBase

This class contains implementation of splitting mask on parts based on distance from borders. Has two modes or working. It may split on parts with same thickness or same volume..

Flow chart of algorithm:

digraph model { "Mask" -> "Voxel distance from background"; "Voxel distance from background" -> "maximum distance"[label=<Equal thickness>] "maximum distance" -> "Bounds" -> "Split voxels in respect of bounds" "Bounds"[label=<Bounds<br /> <FONT POINT-SIZE="10">[0, (maximum distance)/(Number of Parts),<br /> 2*(maximum distance)/(Number of Parts)<br />, ... ,maximum distance]</FONT>>] "Voxel distance from background" -> "Distance histogram"[label=<Equal volume>] "Distance histogram" -> "Create bounds base on histogram" -> "Split voxels in respect of bounds" "Create bounds base on histogram"[label=<Create bounds base on histogram<br /> <FONT POINT-SIZE="10">using histogram bins approximate equal number of voxels in each part</FONT>>] "Distance histogram"[label=<Distance histogram<br /><font point-size="10">of voxels with positive distance <br /> from background </font>>] }

This algorithm has following parameters:

  • num_of_parts (ConstrainedIntValue)- Number of Parts

  • equal_volume (bool)- Equal Volume, If split should be done in respect of parts volume of parts thickness.

classmethod get_name()[source]

Algorithm name. It will be used during interface generating and in registering to proper PartSeg.PartSegCore.algorithm_describe_base.Register.

Return type

str

Returns

name of algorithm

static split(mask, num_of_parts, equal_volume, voxel_size, **_)[source]

This is function which implement calculation.

Parameters
  • mask (ndarray) – area for which rim should be calculated. 2d or 3d numpy array

  • num_of_parts (int) – num of parts on which mask should be split

  • equal_volume (bool) – if split should be on equal volume or equal thick

  • voxel_size – image voxel size

Returns

mask region labelled starting from 1 near border

.roi_info

class PartSegCore.roi_info.BoundInfo(lower: numpy.ndarray, upper: numpy.ndarray)[source]

Bases: NamedTuple

Information about bounding box

box_size()[source]

Size of bounding box

Return type

ndarray

lower: numpy.ndarray

Alias for field number 0

upper: numpy.ndarray

Alias for field number 1

class PartSegCore.roi_info.ROIInfo(roi, annotations=None, alternative=None)[source]

Bases: object

Object to storage meta information about given segmentation. Segmentation array is only referenced, not copied.

Variables
  • ~.roi (numpy.ndarray) – reference to segmentation

  • bound_info (Dict[int,BoundInfo]) – mapping from component number to bounding box

  • sizes (numpy.ndarray) – array with sizes of components

  • annotations (Dict[int, Any]) – annotations of roi

  • alternative (Dict[str, np.ndarray]) – alternative representation of roi

static calc_bounds(roi)[source]

Calculate bounding boxes components

Parameters

roi (np.ndarray) – array for which bounds boxes should be calculated

Returns

mapping component number to bounding box

Return type

Dict[int, BoundInfo]