phenotypic.detect#

Colony/object detectors for agar plate images.

Implements thresholding- and edge-based approaches to turn enhanced grayscale images into binary colony masks, with options suited to faint growth, uneven agar, or dense plates. Includes global histogram methods (Otsu, Li, Yen, Isodata, Triangle, Mean, Minimum), edge-aware variants (Canny), grid-aware detection (Gitter), and watershed-based segmentation for clustered colonies.

class phenotypic.detect.CannyDetector(sigma: float = 1.0, low_threshold: float = 0.1, high_threshold: float = 0.2, use_quantiles: bool = True, min_size: int = 50, invert_edges: bool = True, connectivity: int = 1)[source]#

Bases: ThresholdDetector

Canny edge-based object detection for microbial colonies.

Applies the Canny edge detector to identify colony boundaries, then labels the enclosed regions as individual objects. The Canny algorithm uses a multi-stage process: Gaussian smoothing, gradient calculation, non-maximum suppression, and hysteresis thresholding to produce thin, connected edges that robustly delineate colony perimeters even in noisy or unevenly illuminated images.

Use cases (agar plates): - Detect well-separated colonies with clear boundaries on solid media where

edge sharpness dominates over intensity differences.

  • Handle plates with variable illumination or low contrast that challenge intensity-based thresholding (e.g., translucent colonies on light agar).

  • Segment colonies with heterogeneous internal texture or pigmentation that might fragment under watershed or simple thresholding.

  • Robustly trace colony perimeters when background subtraction is imperfect or when agar texture is pronounced.

Caveats: - Canny assumes objects are defined by edges. Colonies with very diffuse or

gradual boundaries (e.g., fuzzy/mucoid colonies) may yield incomplete or fragmented edges, resulting in under-segmentation or missed objects.

  • Overlapping or touching colonies may be outlined as a single contiguous edge, causing multiple colonies to merge into one object. Pre-blur or increase sigma to regularize boundaries, or use watershed refinement post- detection to split merged regions.

  • Threshold tuning is critical: too aggressive and noise dominates, too conservative and colony boundaries vanish. use_quantiles=True often provides a safer starting point.

  • Does not inherently handle intensity-based segmentation; if colonies differ mainly in brightness (not edges), consider Otsu or watershed instead.

  • May detect plate edges, dust, or scratches as spurious boundaries. Use min_size filtering and ensure clean agar surfaces or pre-mask the plate region if needed.

Parameters:
sigma#

Standard deviation for Gaussian smoothing applied before edge detection, controlling pre-smoothing intensity. Higher values reduce noise sensitivity and suppress spurious edges from agar granularity or scanner artifacts, but may blur fine colony boundaries or merge nearby colonies if set too high. Start with 1–2 for high-resolution images; increase for noisier scans.

Type:

float

low_threshold#

Lower bound for hysteresis thresholding. Raising this suppresses weak edges from noise or faint texture but may fragment colony boundaries if edges are dim. Lowering it recovers more boundary detail but risks false edges. If use_quantiles=True, this is a fraction (0–1) of gradient values; if False, an absolute gradient magnitude.

Type:

float

high_threshold#

Upper bound for hysteresis thresholding. Strong edges above this seed the edge traces; too high and faint colonies lose boundaries, too low and noise creates spurious edges. Adjust relative to low_threshold to control edge connectivity.

Type:

float

use_quantiles#

When True, thresholds are interpreted as quantiles of the gradient distribution (e.g., 0.1 = 10th percentile), making behavior more robust to image-specific intensity ranges. When False, thresholds are absolute gradient magnitudes, requiring manual tuning per imaging setup.

Type:

bool

min_size#

Minimum pixel area to retain as an object after labeling regions enclosed by edges. Increase to remove dust, debris, or imaging artifacts; decrease to capture very small colonies. Setting too high discards genuine small colonies.

Type:

int

invert_edges#

If True (default), regions between edges (i.e., enclosed areas) are labeled as objects, suitable for detecting solid colonies. When False, edges themselves are labeled (useful for atypical cases like ring-shaped colonies or debugging edge quality).

Type:

bool

connectivity#

Connectivity level for labeling regions (1 for 4-connected, 2 for 8-connected in 2D). Higher connectivity merges diagonally adjacent pixels into the same object, which can join fragmented colony regions but may also merge nearby colonies touching at corners.

Type:

int

__del__()#

Automatically stop tracemalloc when the object is deleted.

__getstate__()#

Prepare the object for pickling by disposing of any widgets.

This ensures that UI components (which may contain unpickleable objects like input functions or thread locks) are cleaned up before serialization.

Note

This method modifies the object state by calling dispose_widgets(). Any active widgets will be detached from the object.

__init__(sigma: float = 1.0, low_threshold: float = 0.1, high_threshold: float = 0.2, use_quantiles: bool = True, min_size: int = 50, invert_edges: bool = True, connectivity: int = 1)[source]#
Parameters:
  • sigma (float) – Gaussian smoothing strength before edge detection. Start with 1-2 for clean images; increase for noisy scans to suppress spurious edges. Keep below typical colony radius to avoid merging.

  • low_threshold (float) – Lower hysteresis threshold. If use_quantiles=True, a fraction (e.g., 0.1 = retain edges stronger than 10% of gradients). If False, an absolute gradient magnitude. Increase to suppress weak edges from noise; decrease to recover faint colony boundaries.

  • high_threshold (float) – Upper hysteresis threshold. Seeds edge traces. If use_quantiles=True, a fraction (e.g., 0.2 = top 80% gradients); if False, an absolute magnitude. Raise to focus on strong boundaries; lower to include fainter edges. Must exceed low_threshold.

  • use_quantiles (bool) – Interpret thresholds as quantiles (True, default) or absolute values (False). Quantiles adapt to image contrast automatically, reducing manual tuning.

  • min_size (int) – Minimum object area in pixels. Increase to filter out dust, debris, and small artifacts; decrease to retain tiny colonies.

  • invert_edges (bool) – If True (default), label enclosed regions as objects (colonies). If False, label edge pixels (for atypical cases like ring colonies or edge quality checks).

  • connectivity (int) – Connectivity for labeling regions (1 or 2 in 2D). Higher values merge diagonally touching pixels, useful for bridging fragmented boundaries but may merge touching colonies.

apply(image, inplace=False)#

Binarizes the given image gray using the Yen threshold method.

This function modifies the arr image by applying a binary mask to its enhanced gray (enh_gray). The binarization threshold is automatically determined using Yen’s method. The resulting binary mask is stored in the image’s objmask attribute.

Parameters:

image (Image) – The arr image object. It must have an enh_gray attribute, which is used as the basis for creating the binary mask.

Returns:

The arr image object with its objmask attribute updated

to the computed binary mask other_image.

Return type:

Image

dispose_widgets() None#

Drop references to the UI widgets.

Return type:

None

sync_widgets_from_state() None#

Push internal state into widgets.

Return type:

None

widget(image: Image | None = None, show: bool = False) Widget#

Return (and optionally display) the root widget.

Parameters:
  • image (Image | None) – Optional image to visualize. If provided, visualization controls will be added to the widget.

  • show (bool) – Whether to display the widget immediately. Defaults to False.

Returns:

The root widget.

Return type:

ipywidgets.Widget

Raises:

ImportError – If ipywidgets or IPython are not installed.

class phenotypic.detect.IsodataDetector(ignore_zeros: bool = True, ignore_borders: bool = True)[source]#

Bases: ThresholdDetector

Class for applying ISODATA thresholding to an image.

This class inherits from the ThresholdDetector and provides the functionality to apply ISODATA thresholding method on the enhance matrix (enh_gray) of an arr image. The operation generates a binary mask (objmask) depending on the computed threshold other_image.

Parameters:
  • ignore_zeros (bool)

  • ignore_borders (bool)

apply()#

Applies ISODATA thresholding on the arr image object and modifies its omask attribute accordingly.

__del__()#

Automatically stop tracemalloc when the object is deleted.

__getstate__()#

Prepare the object for pickling by disposing of any widgets.

This ensures that UI components (which may contain unpickleable objects like input functions or thread locks) are cleaned up before serialization.

Note

This method modifies the object state by calling dispose_widgets(). Any active widgets will be detached from the object.

apply(image, inplace=False)#

Binarizes the given image gray using the Yen threshold method.

This function modifies the arr image by applying a binary mask to its enhanced gray (enh_gray). The binarization threshold is automatically determined using Yen’s method. The resulting binary mask is stored in the image’s objmask attribute.

Parameters:

image (Image) – The arr image object. It must have an enh_gray attribute, which is used as the basis for creating the binary mask.

Returns:

The arr image object with its objmask attribute updated

to the computed binary mask other_image.

Return type:

Image

dispose_widgets() None#

Drop references to the UI widgets.

Return type:

None

sync_widgets_from_state() None#

Push internal state into widgets.

Return type:

None

widget(image: Image | None = None, show: bool = False) Widget#

Return (and optionally display) the root widget.

Parameters:
  • image (Image | None) – Optional image to visualize. If provided, visualization controls will be added to the widget.

  • show (bool) – Whether to display the widget immediately. Defaults to False.

Returns:

The root widget.

Return type:

ipywidgets.Widget

Raises:

ImportError – If ipywidgets or IPython are not installed.

class phenotypic.detect.LiDetector(ignore_zeros: bool = True, ignore_borders: bool = True)[source]#

Bases: ThresholdDetector

Class for applying Li’s thresholding to an image.

This class inherits from the ThresholdDetector and provides the functionality to apply Li’s iterative Minimum Cross Entropy thresholding method on the enhance matrix (enh_gray) of an arr image. The operation generates a binary mask (objmask) depending on the computed threshold other_image.

Parameters:
  • ignore_zeros (bool)

  • ignore_borders (bool)

apply()#

Applies Li’s thresholding on the arr image object and modifies its omask attribute accordingly.

__del__()#

Automatically stop tracemalloc when the object is deleted.

__getstate__()#

Prepare the object for pickling by disposing of any widgets.

This ensures that UI components (which may contain unpickleable objects like input functions or thread locks) are cleaned up before serialization.

Note

This method modifies the object state by calling dispose_widgets(). Any active widgets will be detached from the object.

apply(image, inplace=False)#

Binarizes the given image gray using the Yen threshold method.

This function modifies the arr image by applying a binary mask to its enhanced gray (enh_gray). The binarization threshold is automatically determined using Yen’s method. The resulting binary mask is stored in the image’s objmask attribute.

Parameters:

image (Image) – The arr image object. It must have an enh_gray attribute, which is used as the basis for creating the binary mask.

Returns:

The arr image object with its objmask attribute updated

to the computed binary mask other_image.

Return type:

Image

dispose_widgets() None#

Drop references to the UI widgets.

Return type:

None

sync_widgets_from_state() None#

Push internal state into widgets.

Return type:

None

widget(image: Image | None = None, show: bool = False) Widget#

Return (and optionally display) the root widget.

Parameters:
  • image (Image | None) – Optional image to visualize. If provided, visualization controls will be added to the widget.

  • show (bool) – Whether to display the widget immediately. Defaults to False.

Returns:

The root widget.

Return type:

ipywidgets.Widget

Raises:

ImportError – If ipywidgets or IPython are not installed.

class phenotypic.detect.MeanDetector(ignore_zeros: bool = True, ignore_borders: bool = True)[source]#

Bases: ThresholdDetector

Class for applying Mean thresholding to an image.

This class inherits from the ThresholdDetector and provides the functionality to apply Mean thresholding method on the enhance matrix (enh_gray) of an arr image. The operation generates a binary mask (objmask) depending on the computed threshold other_image.

Parameters:
  • ignore_zeros (bool)

  • ignore_borders (bool)

apply()#

Applies Mean thresholding on the arr image object and modifies its omask attribute accordingly.

__del__()#

Automatically stop tracemalloc when the object is deleted.

__getstate__()#

Prepare the object for pickling by disposing of any widgets.

This ensures that UI components (which may contain unpickleable objects like input functions or thread locks) are cleaned up before serialization.

Note

This method modifies the object state by calling dispose_widgets(). Any active widgets will be detached from the object.

apply(image, inplace=False)#

Binarizes the given image gray using the Yen threshold method.

This function modifies the arr image by applying a binary mask to its enhanced gray (enh_gray). The binarization threshold is automatically determined using Yen’s method. The resulting binary mask is stored in the image’s objmask attribute.

Parameters:

image (Image) – The arr image object. It must have an enh_gray attribute, which is used as the basis for creating the binary mask.

Returns:

The arr image object with its objmask attribute updated

to the computed binary mask other_image.

Return type:

Image

dispose_widgets() None#

Drop references to the UI widgets.

Return type:

None

sync_widgets_from_state() None#

Push internal state into widgets.

Return type:

None

widget(image: Image | None = None, show: bool = False) Widget#

Return (and optionally display) the root widget.

Parameters:
  • image (Image | None) – Optional image to visualize. If provided, visualization controls will be added to the widget.

  • show (bool) – Whether to display the widget immediately. Defaults to False.

Returns:

The root widget.

Return type:

ipywidgets.Widget

Raises:

ImportError – If ipywidgets or IPython are not installed.

class phenotypic.detect.MinimumDetector(ignore_zeros: bool = True, ignore_borders: bool = True)[source]#

Bases: ThresholdDetector

Class for applying Minimum thresholding to an image.

This class inherits from the ThresholdDetector and provides the functionality to apply Minimum thresholding method on the enhance matrix (enh_gray) of an arr image. The operation generates a binary mask (objmask) depending on the computed threshold other_image.

Parameters:
  • ignore_zeros (bool)

  • ignore_borders (bool)

apply()#

Applies Minimum thresholding on the arr image object and modifies its omask attribute accordingly.

__del__()#

Automatically stop tracemalloc when the object is deleted.

__getstate__()#

Prepare the object for pickling by disposing of any widgets.

This ensures that UI components (which may contain unpickleable objects like input functions or thread locks) are cleaned up before serialization.

Note

This method modifies the object state by calling dispose_widgets(). Any active widgets will be detached from the object.

apply(image, inplace=False)#

Binarizes the given image gray using the Yen threshold method.

This function modifies the arr image by applying a binary mask to its enhanced gray (enh_gray). The binarization threshold is automatically determined using Yen’s method. The resulting binary mask is stored in the image’s objmask attribute.

Parameters:

image (Image) – The arr image object. It must have an enh_gray attribute, which is used as the basis for creating the binary mask.

Returns:

The arr image object with its objmask attribute updated

to the computed binary mask other_image.

Return type:

Image

dispose_widgets() None#

Drop references to the UI widgets.

Return type:

None

sync_widgets_from_state() None#

Push internal state into widgets.

Return type:

None

widget(image: Image | None = None, show: bool = False) Widget#

Return (and optionally display) the root widget.

Parameters:
  • image (Image | None) – Optional image to visualize. If provided, visualization controls will be added to the widget.

  • show (bool) – Whether to display the widget immediately. Defaults to False.

Returns:

The root widget.

Return type:

ipywidgets.Widget

Raises:

ImportError – If ipywidgets or IPython are not installed.

class phenotypic.detect.OtsuDetector(ignore_zeros: bool = True, ignore_borders: bool = True)[source]#

Bases: ThresholdDetector

Class for applying Otsu’s thresholding to an image.

This class inherits from the ThresholdDetector and provides the functionality to apply Otsu’s thresholding method on the enhance matrix (enh_gray) of an arr image. The operation generates a binary mask (objmask) depending on the computed threshold other_image.

Parameters:
  • ignore_zeros (bool)

  • ignore_borders (bool)

apply()#

Applies Otsu’s thresholding on the arr image object and modifies its omask attribute accordingly.

__del__()#

Automatically stop tracemalloc when the object is deleted.

__getstate__()#

Prepare the object for pickling by disposing of any widgets.

This ensures that UI components (which may contain unpickleable objects like input functions or thread locks) are cleaned up before serialization.

Note

This method modifies the object state by calling dispose_widgets(). Any active widgets will be detached from the object.

apply(image, inplace=False)#

Binarizes the given image gray using the Yen threshold method.

This function modifies the arr image by applying a binary mask to its enhanced gray (enh_gray). The binarization threshold is automatically determined using Yen’s method. The resulting binary mask is stored in the image’s objmask attribute.

Parameters:

image (Image) – The arr image object. It must have an enh_gray attribute, which is used as the basis for creating the binary mask.

Returns:

The arr image object with its objmask attribute updated

to the computed binary mask other_image.

Return type:

Image

dispose_widgets() None#

Drop references to the UI widgets.

Return type:

None

sync_widgets_from_state() None#

Push internal state into widgets.

Return type:

None

widget(image: Image | None = None, show: bool = False) Widget#

Return (and optionally display) the root widget.

Parameters:
  • image (Image | None) – Optional image to visualize. If provided, visualization controls will be added to the widget.

  • show (bool) – Whether to display the widget immediately. Defaults to False.

Returns:

The root widget.

Return type:

ipywidgets.Widget

Raises:

ImportError – If ipywidgets or IPython are not installed.

class phenotypic.detect.RoundPeaksDetector(thresh_method: Literal['otsu', 'mean', 'local', 'triangle', 'minimum', 'isodata'] = 'otsu', subtract_background: bool = True, remove_noise: bool = True, footprint_radius: int = 3, smoothing_sigma: float = 2.0, min_peak_distance: int | None = None, peak_prominence: float | None = None, edge_refinement: bool = True)[source]#

Bases: ObjectDetector

Class for detecting circular colonies in gridded plate images using the gitter algorithm.

The RoundPeaksDetector implements an improved Python version of the gitter colony detection algorithm originally developed for R. This method is specifically designed for quantifying pinned microbial cultures arranged in a regular grid pattern on agar plates. The algorithm works by:

  1. Thresholding the image to create a binary mask of colonies

  2. Analyzing row and column intensity profiles to detect periodic peaks

  3. Estimating grid edges based on peak positions

  4. Assigning pixels to grid cells and identifying dominant colonies

This approach is robust to irregular colonies, noise, variable illumination, and other common plate imaging artifacts.

Note

For best results, use preprocessing such as GaussianBlur or other enhancement techniques before detection. The detector works best with images where colonies are clearly visible against the background.

This detector works best for yeast-like growth where the colonies are circular and less likely to work on filamentous fungi.

Warning

Grid inference from the binary mask alone (when not using GridImage) may be less accurate than providing explicit grid information. For optimal results, use with GridImage when grid parameters are known.

Parameters:
  • thresh_method (Literal['otsu', 'mean', 'local', 'triangle', 'minimum', 'isodata'])

  • subtract_background (bool)

  • remove_noise (bool)

  • footprint_radius (int)

  • smoothing_sigma (float)

  • min_peak_distance (int | None)

  • peak_prominence (float | None)

  • edge_refinement (bool)

thresh_method#

Thresholding method to use for binary mask creation. Options: ‘otsu’, ‘mean’, ‘local’, ‘triangle’, ‘minimum’, ‘isodata’. Default is ‘otsu’.

Type:

str

subtract_background#

Whether to apply white tophat background subtraction before thresholding. Helps with uneven illumination.

Type:

bool

remove_noise#

Whether to apply binary opening to remove small noise artifacts after thresholding.

Type:

bool

footprint_radius#

Radius for morphological operations (noise removal and background subtraction kernels).

Type:

int

smoothing_sigma#

Standard deviation for Gaussian smoothing of row/column sums before peak detection. Higher values increase robustness to noise but may merge nearby peaks. Set to 0 to disable.

Type:

float

min_peak_distance#

Minimum distance between peaks in pixels. If None, automatically estimated from grid dimensions. Prevents detection of spurious peaks too close together.

Type:

int | None

peak_prominence#

Minimum prominence of peaks for detection. If None, automatically estimated from signal statistics. Higher values are more selective.

Type:

float | None

edge_refinement#

Whether to refine grid edges using local intensity profiles. Improves accuracy but adds computational cost.

Type:

bool

References

Wagih, O. and Parts, L. (2014). gitter: a robust and accurate method for quantification of colony sizes from plate images. G3 (Bethesda), 4(3), 547-552. https://omarwagih.github.io/gitter/

__del__()#

Automatically stop tracemalloc when the object is deleted.

__getstate__()#

Prepare the object for pickling by disposing of any widgets.

This ensures that UI components (which may contain unpickleable objects like input functions or thread locks) are cleaned up before serialization.

Note

This method modifies the object state by calling dispose_widgets(). Any active widgets will be detached from the object.

__init__(thresh_method: Literal['otsu', 'mean', 'local', 'triangle', 'minimum', 'isodata'] = 'otsu', subtract_background: bool = True, remove_noise: bool = True, footprint_radius: int = 3, smoothing_sigma: float = 2.0, min_peak_distance: int | None = None, peak_prominence: float | None = None, edge_refinement: bool = True)[source]#

Initialize the RoundPeaksDetector with specified parameters.

Parameters:
  • thresh_method (Literal['otsu', 'mean', 'local', 'triangle', 'minimum', 'isodata']) – Method for thresholding the image. Options are: ‘otsu’ (default), ‘mean’, ‘local’, ‘triangle’, ‘minimum’, ‘isodata’.

  • subtract_background (bool) – If True, apply white tophat transform to remove background variations before thresholding.

  • remove_noise (bool) – If True, apply morphological opening to remove small noise artifacts from the binary mask.

  • footprint_radius (int) – Radius in pixels for morphological operations. Larger values remove larger noise but may erode colony edges.

  • smoothing_sigma (float) – Standard deviation for Gaussian smoothing of intensity profiles before peak detection. Set to 0 to disable smoothing.

  • min_peak_distance (int | None) – Minimum allowed distance between detected peaks. If None, automatically estimated from grid dimensions.

  • peak_prominence (float | None) – Minimum prominence required for peak detection. If None, automatically calculated as 0.1 * signal range.

  • edge_refinement (bool) – If True, refine grid edges using weighted intensity profiles for improved accuracy.

apply(image, inplace=False)#

Binarizes the given image gray using the Yen threshold method.

This function modifies the arr image by applying a binary mask to its enhanced gray (enh_gray). The binarization threshold is automatically determined using Yen’s method. The resulting binary mask is stored in the image’s objmask attribute.

Parameters:

image (Image) – The arr image object. It must have an enh_gray attribute, which is used as the basis for creating the binary mask.

Returns:

The arr image object with its objmask attribute updated

to the computed binary mask other_image.

Return type:

Image

dispose_widgets() None#

Drop references to the UI widgets.

Return type:

None

sync_widgets_from_state() None#

Push internal state into widgets.

Return type:

None

widget(image: Image | None = None, show: bool = False) Widget#

Return (and optionally display) the root widget.

Parameters:
  • image (Image | None) – Optional image to visualize. If provided, visualization controls will be added to the widget.

  • show (bool) – Whether to display the widget immediately. Defaults to False.

Returns:

The root widget.

Return type:

ipywidgets.Widget

Raises:

ImportError – If ipywidgets or IPython are not installed.

class phenotypic.detect.TriangleDetector[source]#

Bases: ThresholdDetector

Detects triangles in an image using a thresholding method.

This class inherits from ThresholdDetector and is specifically designed to detect triangles through a thresholding algorithm applied to the image’s enhance gray. The threshold is calculated using the triangle algorithm, and the result modifies the image’s object mask.

apply()#

Applies triangle thresholding to the enhance gray of the image and updates the object mask accordingly.

__del__()#

Automatically stop tracemalloc when the object is deleted.

__getstate__()#

Prepare the object for pickling by disposing of any widgets.

This ensures that UI components (which may contain unpickleable objects like input functions or thread locks) are cleaned up before serialization.

Note

This method modifies the object state by calling dispose_widgets(). Any active widgets will be detached from the object.

apply(image, inplace=False)#

Binarizes the given image gray using the Yen threshold method.

This function modifies the arr image by applying a binary mask to its enhanced gray (enh_gray). The binarization threshold is automatically determined using Yen’s method. The resulting binary mask is stored in the image’s objmask attribute.

Parameters:

image (Image) – The arr image object. It must have an enh_gray attribute, which is used as the basis for creating the binary mask.

Returns:

The arr image object with its objmask attribute updated

to the computed binary mask other_image.

Return type:

Image

dispose_widgets() None#

Drop references to the UI widgets.

Return type:

None

sync_widgets_from_state() None#

Push internal state into widgets.

Return type:

None

widget(image: Image | None = None, show: bool = False) Widget#

Return (and optionally display) the root widget.

Parameters:
  • image (Image | None) – Optional image to visualize. If provided, visualization controls will be added to the widget.

  • show (bool) – Whether to display the widget immediately. Defaults to False.

Returns:

The root widget.

Return type:

ipywidgets.Widget

Raises:

ImportError – If ipywidgets or IPython are not installed.

class phenotypic.detect.WatershedDetector(footprint: Literal['auto'] | numpy.ndarray | int | None = None, min_size: int = 50, compactness: float = 0.001, connectivity: int = 1, relabel: bool = True, ignore_zeros: bool = True)[source]#

Bases: ThresholdDetector

Class for detecting objects in an image using the Watershed algorithm.

The WatershedDetector class processes images to detect and segment objects by applying the watershed algorithm. This class extends the capabilities of ThresholdDetector and includes customization for parameters such as footprint size, minimum object size, compactness, and connectivity. This is useful for image segmentation tasks, where proximity-based object identification is needed.

Note

Its recommended to use GaussianBlur beforehand

Parameters:
  • footprint (Literal['auto'] | np.ndarray | int | None)

  • min_size (int)

  • compactness (float)

  • connectivity (int)

  • relabel (bool)

  • ignore_zeros (bool)

footprint#

Structure element to define the neighborhood for dilation and erosion operations. Can be specified directly as ‘auto’, an ndarray, an integer for diamond size, or None for implementation-based determination.

Type:

Literal[‘auto’] | np.ndarray | int | None

min_size#

Minimum size of objects to retain during segmentation. Objects smaller than this other_image are removed.

Type:

int

compactness#

Compactness parameter controlling segment shapes. Higher values enforce more regularly shaped objects.

Type:

float

connectivity#

The connectivity level used for determining connected components. Represents the number of dimensions neighbors need to share (1 for fully connected, higher values for less connectivity).

Type:

int

relabel#

Whether to relabel segmented objects during processing to ensure consistent labeling.

Type:

bool

ignore_zeros#

Whether to exclude zero-valued pixels from threshold calculation. When True, Otsu threshold is calculated using only non-zero pixels, and zero pixels are automatically treated as background. When False, all pixels (including zeros) are used for threshold calculation. Default is True, which is useful for microscopy images where zero pixels represent true background or imaging artifacts.

Type:

bool

__del__()#

Automatically stop tracemalloc when the object is deleted.

__getstate__()#

Prepare the object for pickling by disposing of any widgets.

This ensures that UI components (which may contain unpickleable objects like input functions or thread locks) are cleaned up before serialization.

Note

This method modifies the object state by calling dispose_widgets(). Any active widgets will be detached from the object.

apply(image, inplace=False)#

Binarizes the given image gray using the Yen threshold method.

This function modifies the arr image by applying a binary mask to its enhanced gray (enh_gray). The binarization threshold is automatically determined using Yen’s method. The resulting binary mask is stored in the image’s objmask attribute.

Parameters:

image (Image) – The arr image object. It must have an enh_gray attribute, which is used as the basis for creating the binary mask.

Returns:

The arr image object with its objmask attribute updated

to the computed binary mask other_image.

Return type:

Image

dispose_widgets() None#

Drop references to the UI widgets.

Return type:

None

sync_widgets_from_state() None#

Push internal state into widgets.

Return type:

None

widget(image: Image | None = None, show: bool = False) Widget#

Return (and optionally display) the root widget.

Parameters:
  • image (Image | None) – Optional image to visualize. If provided, visualization controls will be added to the widget.

  • show (bool) – Whether to display the widget immediately. Defaults to False.

Returns:

The root widget.

Return type:

ipywidgets.Widget

Raises:

ImportError – If ipywidgets or IPython are not installed.

class phenotypic.detect.YenDetector(ignore_zeros: bool = True, ignore_borders: bool = True)[source]#

Bases: ThresholdDetector

Class for applying Yen’s thresholding to an image.

This class inherits from the ThresholdDetector and provides the functionality to apply Yen’s thresholding method on the enhance gray (enh_gray) of an arr image. The operation generates a binary mask (objmask) depending on the computed threshold other_image.

Parameters:
  • ignore_zeros (bool)

  • ignore_borders (bool)

apply()#

Applies Yen’s thresholding on the arr image object and modifies its omask attribute accordingly.

__del__()#

Automatically stop tracemalloc when the object is deleted.

__getstate__()#

Prepare the object for pickling by disposing of any widgets.

This ensures that UI components (which may contain unpickleable objects like input functions or thread locks) are cleaned up before serialization.

Note

This method modifies the object state by calling dispose_widgets(). Any active widgets will be detached from the object.

apply(image, inplace=False)#

Binarizes the given image gray using the Yen threshold method.

This function modifies the arr image by applying a binary mask to its enhanced gray (enh_gray). The binarization threshold is automatically determined using Yen’s method. The resulting binary mask is stored in the image’s objmask attribute.

Parameters:

image (Image) – The arr image object. It must have an enh_gray attribute, which is used as the basis for creating the binary mask.

Returns:

The arr image object with its objmask attribute updated

to the computed binary mask other_image.

Return type:

Image

dispose_widgets() None#

Drop references to the UI widgets.

Return type:

None

sync_widgets_from_state() None#

Push internal state into widgets.

Return type:

None

widget(image: Image | None = None, show: bool = False) Widget#

Return (and optionally display) the root widget.

Parameters:
  • image (Image | None) – Optional image to visualize. If provided, visualization controls will be added to the widget.

  • show (bool) – Whether to display the widget immediately. Defaults to False.

Returns:

The root widget.

Return type:

ipywidgets.Widget

Raises:

ImportError – If ipywidgets or IPython are not installed.