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, 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": {
         "anyOf": [
            {
               "type": "object"
            },
            {
               "$ref": "#/$defs/BaseModel"
            }
         ],
         "title": "Values"
      },
      "class_path": {
         "default": "",
         "title": "Class Path",
         "type": "string"
      }
   },
   "$defs": {
      "BaseModel": {
         "properties": {},
         "title": "BaseModel",
         "type": "object"
      }
   },
   "additionalProperties": false,
   "required": [
      "name",
      "values"
   ]
}

Config:
  • extra: str = forbid

  • smart_union: bool = True

Fields:
field class_path: str = ''
field name: str [Required]
field values: Union[Dict[str, Any], BaseModel] [Required]
class Config[source]
algorithm()[source]
classmethod check_name(v)[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 :type replace: :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])

classmethod update_class_path(v, values)[source]
classmethod update_values(v, values)[source]
val_serializer(value, _info)[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"
      }
   },
   "additionalProperties": false,
   "required": [
      "name",
      "algorithm",
      "values"
   ]
}

Config:
  • extra: str = forbid

Fields:
field algorithm: str [Required]
field name: str [Required]
field values: Any [Required]
pretty_print(algorithm_dict)[source]
classmethod validate_values(v, 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 :type class_methods: :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 :type methods: :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)

Convert pydantic model to list of AlgorithmPropert nad strings.

Parameters:

obj (Type[BaseModel])

Return type:

List[Union[AlgorithmProperty, str]]

Returns:

PartSegCore.algorithm_describe_base.base_model_to_algorithm_property_pydantic_1(obj)[source]

Convert pydantic model to list of AlgorithmPropert nad strings.

Parameters:

obj (Type[BaseModel])

Return type:

List[Union[AlgorithmProperty, str]]

Returns:

PartSegCore.algorithm_describe_base.base_model_to_algorithm_property_pydantic_2(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, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

class PartSegCore.image_operations.RadiusType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: 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: Encoder

.io_utils

class PartSegCore.io_utils.LoadBase[source]

Bases: _IOBase, 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: 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: 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: 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: ndarray

Alias for field number 1

class PartSegCore.io_utils.SaveBase[source]

Bases: _IOBase, 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: 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.SaveROIAsNumpy[source]

Bases: 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: 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: 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=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.SegmentationType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

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: 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": "#/$defs/RadiusType"
      },
      "dilate_radius": {
         "title": "Dilate Radius",
         "type": "integer"
      },
      "fill_holes": {
         "$ref": "#/$defs/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": {
         "default": false,
         "title": "Reversed Mask",
         "type": "boolean"
      }
   },
   "$defs": {
      "RadiusType": {
         "description": "If operation should be performed and if on each layer separately on globally",
         "enum": [
            0,
            1,
            2
         ],
         "title": "RadiusType",
         "type": "integer"
      }
   },
   "additionalProperties": false,
   "required": [
      "dilate",
      "dilate_radius",
      "fill_holes",
      "max_holes_size",
      "save_components",
      "clip_to_mask"
   ]
}

Config:
  • extra: str = forbid

Fields:
field clip_to_mask: bool [Required]
field dilate: RadiusType [Required]
field dilate_radius: int [Required]
field fill_holes: 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

pydantic model PartSegCore.project_info.HistoryElement[source]

Bases: BaseModel

Show JSON schema
{
   "title": "HistoryElement",
   "type": "object",
   "properties": {
      "roi_extraction_parameters": {
         "title": "Roi Extraction Parameters",
         "type": "object"
      },
      "annotations": {
         "anyOf": [
            {
               "type": "object"
            },
            {
               "type": "null"
            }
         ],
         "title": "Annotations"
      },
      "mask_property": {
         "$ref": "#/$defs/MaskProperty"
      },
      "arrays": {
         "default": null,
         "title": "Arrays"
      }
   },
   "$defs": {
      "MaskProperty": {
         "additionalProperties": false,
         "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)",
         "properties": {
            "dilate": {
               "$ref": "#/$defs/RadiusType"
            },
            "dilate_radius": {
               "title": "Dilate Radius",
               "type": "integer"
            },
            "fill_holes": {
               "$ref": "#/$defs/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": {
               "default": false,
               "title": "Reversed Mask",
               "type": "boolean"
            }
         },
         "required": [
            "dilate",
            "dilate_radius",
            "fill_holes",
            "max_holes_size",
            "save_components",
            "clip_to_mask"
         ],
         "title": "MaskProperty",
         "type": "object"
      },
      "RadiusType": {
         "description": "If operation should be performed and if on each layer separately on globally",
         "enum": [
            0,
            1,
            2
         ],
         "title": "RadiusType",
         "type": "integer"
      }
   },
   "additionalProperties": false,
   "required": [
      "roi_extraction_parameters",
      "annotations",
      "mask_property"
   ]
}

Config:
  • extra: str = forbid

  • arbitrary_types_allowed: bool = True

Fields:
field annotations: Optional[Dict[int, Any]] [Required]
field arrays: BytesIO [Required]
field mask_property: MaskProperty [Required]
field roi_extraction_parameters: Dict[str, Any] [Required]
class Config[source]

Bases: object

classmethod create(roi_info, mask, roi_extraction_parameters, mask_property)[source]
get_roi_info_and_mask()[source]
Return type:

Tuple[ROIInfo, Optional[ndarray]]

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

PartSegCore.project_info.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 also for others.

class PartSegCore.mask_partition_utils.BorderRim[source]

Bases: 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 (float)- 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

pydantic model PartSegCore.mask_partition_utils.BorderRimParameters[source]

Bases: BaseModel

Show JSON schema
{
   "title": "BorderRimParameters",
   "type": "object",
   "properties": {
      "distance": {
         "default": 500,
         "maximum": 1000000.0,
         "minimum": 0.0,
         "title": "Distance",
         "type": "number"
      },
      "units": {
         "allOf": [
            {
               "$ref": "#/$defs/Units"
            }
         ],
         "default": 2
      }
   },
   "$defs": {
      "Units": {
         "enum": [
            0,
            1,
            2,
            3
         ],
         "title": "Units",
         "type": "integer"
      }
   },
   "additionalProperties": false
}

Config:
  • extra: str = forbid

Fields:
field distance: float = 500
Constraints:
  • ge = 0

  • le = 1000000

field units: Units = Units.nm
class PartSegCore.mask_partition_utils.MaskDistanceSplit[source]

Bases: 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 (int)- 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

pydantic model PartSegCore.mask_partition_utils.MaskDistanceSplitParameters[source]

Bases: BaseModel

Show JSON schema
{
   "title": "MaskDistanceSplitParameters",
   "type": "object",
   "properties": {
      "num_of_parts": {
         "default": 2,
         "maximum": 1024,
         "minimum": 1,
         "title": "Number of Parts",
         "type": "integer"
      },
      "equal_volume": {
         "default": false,
         "description": "If split should be done in respect of parts volume of parts thickness.",
         "title": "Equal Volume",
         "type": "boolean"
      }
   },
   "additionalProperties": false
}

Config:
  • extra: str = forbid

Fields:
field equal_volume: bool = False

If split should be done in respect of parts volume of parts thickness.

field num_of_parts: int = 2
Constraints:
  • ge = 1

  • le = 1024

.roi_info

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

Bases: NamedTuple

Information about bounding box

box_size()[source]

Size of bounding box

Return type:

ndarray

lower: ndarray

Alias for field number 0

upper: 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]