phenotypic.detect#
Colony/object detectors for agar plate images.
Implements thresholding- and edge-based approaches to turn detection matrix 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, Manual), edge-aware variants (Canny), grid-aware detection (Gitter), and watershed-based segmentation for clustered colonies.
Classes
Detect colonies by Canny edge detection and enclosed-region labelling. |
|
Detect colonies by region-based level-set segmentation using the Chan-Vese energy functional. |
|
Detect colonies by combining multiple detectors via union, intersection, or overlap filtering. |
|
Detect and separate filamentous fungal colonies by two-stage detection with Euclidean Voronoi partition. |
|
Detect colonies by dual-threshold hysteresis, bridging bright cores to faint edges. |
|
Detect inoculation sites on agar plates via Gaussian background subtraction and multi-scale blob enhancement. |
|
Detect colonies by MAD-based noise estimation and hysteresis thresholding. |
|
Detect colonies by iterative ISODATA clustering of the intensity histogram. |
|
Detect colonies by minimising cross-entropy between the original and thresholded image. |
|
Detect colonies by applying a user-specified intensity threshold. |
|
Detect colonies by stamping footprint masks at evenly-spaced grid positions derived from reference coordinates. |
|
Detect objects by stamping footprint masks at user-specified coordinates. |
|
Detect colonies by thresholding at the mean image intensity. |
|
Detect colonies by finding the valley between two histogram peaks. |
|
Detect colonies by global Otsu thresholding on bimodal plate histograms. |
|
Detect colonies by adaptive local Otsu thresholding within a sliding footprint. |
|
Detect round colonies on gridded plates by row/column peak analysis (gitter algorithm). |
|
Detect colonies by two-stage Otsu thresholding with per-object refinement. |
|
Detect colonies on gridded plates using sinusoidal cross-correlation peak finding. |
|
Detect colonies by triangle thresholding on skewed, background-dominant plate histograms. |
|
Detect and separate touching colonies by watershed segmentation on a distance-transform surface. |
|
Detect colonies by maximising the correlation between the original and binarised image. |
- 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 = 2)[source]
Bases:
ThresholdDetectorDetect colonies by Canny edge detection and enclosed-region labelling.
Apply multi-stage Canny edge detection (Gaussian smoothing, gradient magnitude, non-maximum suppression, hysteresis thresholding) to produce thin, connected boundary contours, then label the enclosed regions as individual colonies. This edge-based approach segments colonies by boundary contrast rather than absolute intensity, making it effective on plates with uneven illumination or translucent colonies. For a full comparison see Detection Strategies Compared.
- Parameters:
sigma (float) – Gaussian smoothing standard deviation before edge detection (default 1.0). Higher values suppress noise and spurious edges but may blur fine boundaries or merge nearby colonies. Typical range: 0.5–3.0. Start with 1.0 for clean images; increase to 2.0–3.0 for noisy scans.
low_threshold (float) – Lower hysteresis threshold (default 0.1). When use_quantiles is True, this is a fraction (0.1 = retain edges stronger than 10 % of gradient magnitudes). When False, an absolute gradient value. Increase to suppress weak noise edges. Typical quantile range: 0.05–0.2.
high_threshold (float) – Upper hysteresis threshold seeding edge traces (default 0.2). Same interpretation as low_threshold. Must exceed low_threshold. Typical quantile range: 0.1–0.4.
use_quantiles (bool) – If True (default), interpret thresholds as gradient- magnitude quantiles, adapting automatically to image contrast. Set to False for absolute gradient values when imaging conditions are tightly controlled.
min_size (int) – Minimum object area in pixels (default 50). Increase to filter dust, debris, and plate-edge artefacts; decrease to retain tiny colonies. Typical range: 20–500.
invert_edges (bool) – If True (default), label enclosed regions as colony objects. If False, label edge pixels themselves (useful for debugging edge quality).
connectivity (int) – Connectivity for region labelling (1 = 4-connected, 2 = 8-connected; default 2). Higher connectivity bridges diagonal gaps in edge contours.
- Returns:
Input image with
objmapset to a labelled colony map where each enclosed region receives a unique integer label.objmaskis derived from the non-zero region of the label map.- Return type:
Image
- Raises:
ValueError – If high_threshold is less than low_threshold or if threshold values are outside the valid range.
- Best For:
Well-separated colonies on solid media where colony edges are sharper than intensity differences relative to background.
Translucent or lightly pigmented colonies that lack sufficient intensity contrast for threshold-based methods.
Plates with heterogeneous colony texture or pigmentation that fragments under watershed or simple thresholding.
Images with moderate vignetting where edge contrast is preserved even though absolute intensity varies spatially.
- Consider Also:
OtsuDetectorwhen colonies differ from background primarily in brightness rather than edge contrast.WatershedDetectorwhen touching colonies must be split by region-growing from interior seeds.HysteresisDetectorwhen dual-threshold intensity segmentation is preferred over edge-based detection.
References
[1] J. Canny, “A computational approach to edge detection,” IEEE Trans. Pattern Anal. Mach. Intell., vol. 8, no. 6, pp. 679–698, 1986.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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 = 2)[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 width 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)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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.ChanVeseDetector(mu: float = 0.25, lambda1: float = 1.0, lambda2: float = 1.0, max_num_iter: int = 500, tol: float = 0.001, dt: float = 0.5, init_level_set: str = 'checkerboard', min_size: int = 50, connectivity: int = 2)[source]
Bases:
ObjectDetectorDetect colonies by region-based level-set segmentation using the Chan-Vese energy functional.
Partition the image into foreground and background by minimising an energy functional based on intensity homogeneity within each region. Because segmentation is driven by region statistics rather than edge gradients, colonies with diffuse boundaries, uneven texture, or gradual transitions into the agar background are captured cleanly. For algorithm details see Detection Strategies Compared.
- Parameters:
mu (float) – Edge-length penalty weight. Higher values produce smoother, rounder colony outlines; lower values preserve fine boundary detail. Typical range: 0.05–1.0. Default: 0.25.
lambda1 (float) – Weight for intensity deviation inside detected regions. Increase to enforce uniform colony brightness. Default: 1.0.
lambda2 (float) – Weight for intensity deviation outside detected regions. Increase when the agar background is homogeneous. Default: 1.0.
max_num_iter (int) – Maximum level-set iterations. Increase for complex images where convergence is slow; decrease for faster (but potentially incomplete) segmentation. Default: 500.
tol (float) – Convergence tolerance (L2 norm of level-set change). Smaller values require tighter convergence but more iterations. Default: 1e-3.
dt (float) – Step-size multiplier for level-set evolution. Larger values evolve faster but risk instability. Default: 0.5.
init_level_set (str) – Initialisation method for the level set. Accepted values:
"checkerboard","disk","small disk". Checkerboard is robust for most plate images. Default:"checkerboard".min_size (int) – Minimum colony area in pixels. Connected components smaller than this are removed as noise. Default: 50.
connectivity (int) – Pixel connectivity for labelling connected components.
1for 4-connectivity,2for 8-connectivity. Default: 2.
- Returns:
Input image with
objmaskset to binary mask andobjmapset to labeled connected components.- Return type:
Image
- Raises:
ValueError – If
init_level_setis not a recognised initialisation method.
- Best For:
Mucoid or fuzzy colonies whose edges lack sharp intensity gradients.
Plates with uneven colony pigmentation or heterogeneous surface texture that fragments threshold-based masks.
Low-contrast imaging where colony and agar intensities are similar.
Morphology studies where smooth, accurate colony outlines are required.
- Consider Also:
OtsuDetectorwhen colonies and background form two clear histogram peaks and a fast global threshold suffices.HysteresisDetectorwhen colony brightness varies but edges are still reasonably sharp.CannyDetectorwhen colonies are best delineated by edge contrast rather than region homogeneity.
References
[1] T. F. Chan and L. A. Vese, “Active contours without edges,” IEEE Trans. Image Process., vol. 10, no. 2, pp. 266–277, 2001.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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.CompositeDetector(detectors: List[ObjectDetector | 'ImagePipeline'] = None, mode: Literal['union', 'intersection', 'overlap'] = 'overlap', min_overlap_ratio: float = 0.0)[source]
Bases:
ObjectDetectorDetect colonies by combining multiple detectors via union, intersection, or overlap filtering.
Apply two or more detection algorithms (or preprocessing pipelines ending in a detector) to the same plate image and merge their binary masks. Ensemble combination improves sensitivity (union), specificity (intersection), or both (overlap filtering). This is especially useful for challenging plates where no single algorithm captures all colonies reliably. For a full comparison see Detection Strategies Compared.
- Parameters:
detectors (List[Union[ObjectDetector, 'ImagePipeline']]) – List of
ObjectDetectororImagePipelineinstances to combine. Pipelines allow preprocessing steps before detection. Defaults to[OtsuDetector(), RoundPeaksDetector()]when not specified.mode (Literal['union', 'intersection', 'overlap']) – Combination strategy.
'union'marks a pixel as colony if any detector flags it (logical OR, maximises sensitivity).'intersection'requires all detectors to agree (logical AND, maximises specificity).'overlap'retains whole objects that have mutual spatial overlap across masks (balances sensitivity and specificity). Default'overlap'.min_overlap_ratio (float) – For
'overlap'mode, minimum fraction of object pixels that must overlap with all other masks. Range: 0.0–1.0. Default 0.0. Higher values produce more conservative filtering. Typical range: 0.0–0.5.
- Returns:
Input image with
objmaskset to the combined binary colony mask andobjmapderived from the merged mask.- Return type:
Image
- Raises:
ValueError – If detectors list is empty or mode is not one of
'union','intersection', or'overlap'.
- Best For:
Plates where different colony sub-populations respond to different detection algorithms (e.g., bright colonies via Otsu, faint colonies via triangle thresholding).
Consensus-based quality control that accepts only colonies confirmed by all methods.
Ensemble strategies that maximise recall by unioning masks from complementary algorithms.
Benchmarking workflows that compare detector agreement.
- Consider Also:
OtsuDetectororHysteresisDetectorwhen a single detector already captures all colonies reliably.WatershedDetectorwhen the primary challenge is separating touching colonies rather than combining detection strategies.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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.FilamentousFungiDetector(inoculum_detector: ObjectDetector | ImagePipeline | None = None, max_colony_radius_px: float = 250.0, min_branch_width_px: int = 3, ignore_borders: bool = True, edge_noise_threshold: float = 6.0, reconnection_tolerance: float = 2.5, max_gap_length: int = 30, border_margin_px: int = 50, frag_reach_px: int = 10, gap_crossing_penalty: float = 4.0, *, gauss_sigma: float | None = None, tile_size: int | None = None, tile_overlap: int | None = None, pct_min_wavelength: float | None = None, mad_window: int | None = None, path_dilation_radius: int | None = None, snr_margin: int | None = None, coherence_window_radius: int | None = None)[source]
Bases:
GridObjectDetectorDetect and separate filamentous fungal colonies by two-stage detection with Euclidean Voronoi partition.
Segment filamentous fungi in two stages: (1) detect compact inoculation centres with an
inoculum_detector, (2) capture the full hyphal structure via phase-congruency-based branch detection and Dijkstra reconnection. Filtered centre centroids seed a Euclidean Voronoi partition that assigns every fungal pixel to its nearest colony, with connectivity-based correction ensuring uniform labelling within connected components. For a full comparison see Detection Strategies Compared.- Parameters:
inoculum_detector (Union[ObjectDetector, 'ImagePipeline', None]) – ObjectDetector or ImagePipeline that identifies compact fungal centres/nuclei. Should produce small, tight regions at inoculation points. Default uses an internal InoculumDetector + GridSectionLargest pipeline.
max_colony_radius_px (float) – Largest colony radius (in pixels) the detector should handle. Sizes scene-derived spatial parameters (
gauss_sigma,tile_size,tile_overlap) for this worst case. Default 250.min_branch_width_px (int) – Narrowest hyphal branch width (in pixels) to detect. Sizes signal-scale parameters (
pct_min_wavelength,mad_window,path_dilation_radius,snr_margin,coherence_window_radius). Default 3.ignore_borders (bool) – If True, drops objects touching the image border during hysteresis-threshold branch detection. Default True.
edge_noise_threshold (float) – Noise threshold scaling factor for phase congruency edge detection. Higher values are stricter (reject more pixels as noise; preserve fewer thin hyphae). Default 6.0.
reconnection_tolerance (float) – IQR multiplier for path quality threshold calibration. Higher values accept more reconnection paths (may bridge genuinely-missing hyphae but risks over-merging). Default 2.5.
max_gap_length (int) – Maximum acceptable length (pixels) of a suspicious cost stretch along a reconnection path. Paths with longer bad stretches are rejected. Default 30.
border_margin_px (int) – Border penalty buffer width in pixels. Prevents reconnection paths from routing along image borders. Default 50.
frag_reach_px (int) – Maximum 2D distance (pixels) from a fragment’s boundary to the nearest routable (low-cost) pixel. Fragments more isolated than this are dropped before Dijkstra routing, since no plausible path could connect them. Default 10.
gap_crossing_penalty (float) – Distance-gap penalty strength during Dijkstra routing. Higher values make paths route around low-PCT-energy gaps more aggressively. Default 4.0.
gauss_sigma (Optional[float]) – Override for SubtractGaussian sigma. If None (default), derived from
max_colony_radius_px.tile_size (Optional[int]) – Override for tile side length. If None (default), derived from
max_colony_radius_px.tile_overlap (Optional[int]) – Override for tile overlap. If None (default), derived from
max_colony_radius_px.pct_min_wavelength (Optional[float]) – Override for log-Gabor minimum wavelength. If None (default), derived from
min_branch_width_px.mad_window (Optional[int]) – Override for local MAD window size (must be odd). If None (default), derived from
min_branch_width_px.path_dilation_radius (Optional[int]) – Override for dilating reconnection paths. If None (default), derived from
min_branch_width_px.snr_margin (Optional[int]) – Override for SNR background ring radius beyond
path_dilation_radius. If None (default), derived frommin_branch_width_px.coherence_window_radius (Optional[int]) – Override for orientation coherence computation radius. If None (default), derived from
min_branch_width_px.
- Returns:
Input image with
objmaskset to a binary fungal mask andobjmapset to a labelled colony map where each fungal colony receives a unique integer label via Voronoi assignment.- Return type:
Image
- Raises:
TypeError – If inoculum_detector is not an ObjectDetector or ImagePipeline instance.
ValueError – If no centres are detected, no branch structure is detected, or no centres overlap with the branch structure after filtering.
- Best For:
Filamentous fungal colonies (e.g., Aspergillus, Neurospora, Trichoderma) with irregular, spreading hyphal morphologies.
Dense plates where neighbouring fungal colonies touch or overlap and must be individually labelled.
Time-course experiments tracking hyphal extension from compact inoculation sites.
Grid-based fungal culture plates (GridImage) where one colony per well must be quantified.
High-throughput fungal phenotyping screens requiring consistent separation quality across hundreds of plates.
- Consider Also:
WatershedDetectorwhen colonies are compact and roughly circular (yeast-like morphology).OtsuDetectorwhen fungi are well-separated and a simple binary mask suffices without individual labelling.CompositeDetectorwhen combining multiple detection strategies without the two-stage centre-plus-body approach.
References
[1] P. Kovesi, “Image features from phase congruency,” Videre: J. Comput. Vis. Res., vol. 1, no. 3, pp. 1–26, 1999.
See also
- Tutorial 10: Detecting Filamentous Fungi
Dedicated tutorial for filamentous fungi detection workflows.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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.
- beta: float = 2.0
- delta: float = 1.0
- gamma: float = 1.2
- gauss_n_iter: int = 2
- pct_n_orient: int = 8
- class phenotypic.detect.HysteresisDetector(low: str | float = 'mean', high: str | float = 'otsu', ignore_zeros: bool = False, ignore_borders: bool = True)[source]
Bases:
ThresholdDetectorDetect colonies by dual-threshold hysteresis, bridging bright cores to faint edges.
Seed strong colony regions that exceed the high threshold and expand each seed via pixel connectivity to include neighbouring pixels above the low threshold. This two-pass approach captures colonies whose intensity varies from bright centres to faint margins – a common pattern across growth stages and under uneven illumination. For a full comparison see Detection Strategies Compared.
- Parameters:
low (Union[str, float]) – Lower threshold controlling expansion sensitivity. Accepts a method name (
'otsu','triangle','li','yen','isodata','mean','minimum') for automatic computation, or a float for a manual value (0–255 for 8-bit, 0–65535 for 16-bit). Default'mean'. Lower values include more faint colony pixels but increase false positives. Typical tuning: start with'mean'and switch to a numeric value if automatic methods are too aggressive or too conservative.high (Union[str, float]) – Upper threshold seeding strong colony regions. Same format as low. Default
'otsu'. Must be >= low after computation. Higher values restrict seeds to the brightest colony pixels, producing fewer but higher-confidence detections.ignore_zeros (bool) – If True (default), exclude zero-intensity pixels from automatic threshold computation. Enable for plates with black borders or masked regions.
ignore_borders (bool) – If True (default), remove colonies touching image edges via
clear_border(). Recommended for grid-based colony counting.
- Returns:
Input image with
objmaskset to a binary colony mask where True pixels are colony foreground (including faint pixels connected to strong seed regions).objmapis not modified.- Return type:
Image
- Raises:
ValueError – If the computed high threshold is less than the computed low threshold, or if an unrecognised threshold method name is provided.
- Best For:
Plates where colony brightness varies (e.g., young versus mature growth, or centre-to-edge intensity gradients within a colony).
Noisy agar backgrounds where isolated noise pixels sit above a single threshold but lack connectivity to true colony regions.
Moderate vignetting or lighting gradients that cause a single global threshold to over- or under-segment parts of the plate.
Mixed-species plates where different organisms produce colonies of different intensities on the same agar.
- Consider Also:
OtsuDetectorwhen colony and background peaks are balanced and a single threshold suffices.WatershedDetectorwhen touching colonies must be split into individually labelled regions.CannyDetectorwhen colonies are best delineated by edge contrast rather than intensity.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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.InoculumDetector(min_diameter: float = 30.0, max_diameter: float = 100.0, thresh_method: Literal['otsu', 'mean', 'local', 'triangle', 'minimum', 'isodata', 'li'] = 'otsu', enable_gmm: bool = True, gmm_n_components: int = 2, gmm_separation_threshold: float = 0.9, validate_obj_count: bool = True)[source]
Bases:
ObjectDetectorDetect inoculation sites on agar plates via Gaussian background subtraction and multi-scale blob enhancement.
Identify inoculation spots (from pin-deposition tools, liquid spotting, or serial dilutions) by composing Gaussian background subtraction, median filtering, multi-scale Laplacian-of-Gaussian blob enhancement, contrast stretching, morphological opening, round-peaks detection, and optional GMM-based core extraction. All processing occurs on a working copy so that
image.detect_matis never modified. For a full comparison see Detection Strategies Compared.- Parameters:
min_diameter (float) – Smallest expected inoculum diameter in pixels. Used to derive LoG minimum radius and GMM morphological parameters. Set based on the smallest visible spot in your images. Default 30.0. Typical range: 5–80.
max_diameter (float) – Largest expected inoculum diameter in pixels. Used to derive Gaussian background subtraction sigma and LoG maximum radius. Default 100.0. Typical range: 50–300. Must be greater than min_diameter.
thresh_method (Literal['otsu', 'mean', 'local', 'triangle', 'minimum', 'isodata', 'li']) – Thresholding method for binary segmentation within the RoundPeaksDetector step. Options:
'otsu'(default),'mean','local','triangle','minimum','isodata','li'.'otsu'works well for most standardised setups;'local'adapts to spatial illumination gradients.enable_gmm (bool) – If True (default), apply Gaussian Mixture Model core extraction to refine detected regions to bright, compact cores. Disable for inocula that lack clear core-surround structure.
gmm_n_components (int) – GMM components per region (default 2). 2 separates core from surround; increase only for complex multi-layered spots.
gmm_separation_threshold (float) – Normalised Euclidean distance between GMM component means. Below this threshold a region is left unmodified (no clear core). Default 0.9. Typical range: 0.8–1.2. Increase to make refinement less aggressive.
validate_obj_count (bool) – If True (default) and the input is a
GridImage, raiseValueErrorwhen the detected object count exceedsnrows * ncols. Catches over-segmentation early.
- Returns:
Input image with
objmask(binary inoculum mask) andobjmap(labelled inoculum map) populated.- Return type:
Image
- Raises:
ValueError – If detected object count exceeds grid capacity (when validate_obj_count is True and input is a GridImage), or if min_diameter >= max_diameter.
- Best For:
Pin-tool inoculation on high-density plates (96-well, 384-well) where inocula are 30–80 pixels in diameter.
Spot-dilution assays producing 10–150 pixel inocula across serial dilution series.
Pre-growth phenotyping baselines (T=0 imaging) for establishing reference coordinates before growth measurements.
Liquid spotting assays where GMM core extraction refines boundaries for accurate area and circularity measurements.
- Consider Also:
RoundPeaksDetectorwhen colonies (not inocula) must be detected on a regular grid without multi-scale blob enhancement.OtsuDetectorwhen inocula are high-contrast and a simple global threshold is sufficient.FilamentousFungiDetectorwhen inoculation sites have developed into filamentous fungal growth.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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__(min_diameter: float = 30.0, max_diameter: float = 100.0, thresh_method: Literal['otsu', 'mean', 'local', 'triangle', 'minimum', 'isodata', 'li'] = 'otsu', enable_gmm: bool = True, gmm_n_components: int = 2, gmm_separation_threshold: float = 0.9, validate_obj_count: bool = True)[source]
Initialise InoculumDetector with biology-driven parameters.
- Parameters:
min_diameter (float) – Smallest expected inoculum diameter (pixels). Default: 30.0.
max_diameter (float) – Largest expected inoculum diameter (pixels). Default: 100.0.
thresh_method (Literal['otsu', 'mean', 'local', 'triangle', 'minimum', 'isodata', 'li']) – Thresholding method. Default:
'otsu'.enable_gmm (bool) – Apply GMM core extraction. Default: True.
gmm_n_components (int) – GMM components per region. Default: 2.
gmm_separation_threshold (float) – GMM mean separation threshold. Default: 0.9.
validate_obj_count (bool) – Validate object count for GridImage. Default: True.
- apply(image, inplace=False)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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 = False, ignore_borders: bool = True)[source]
Bases:
ThresholdDetectorDetect colonies by iterative ISODATA clustering of the intensity histogram.
Iteratively partition pixels into foreground and background classes by computing class means, then refine the threshold until convergence. The resulting binary mask separates colony pixels from agar background. Works best when both classes have similar variance and roughly balanced pixel counts. For a full comparison see Detection Strategies Compared.
- Parameters:
ignore_zeros (bool) – Exclude zero-intensity pixels from threshold computation. Enable for plates with black borders or masked regions; disable only when zero is a meaningful intensity value. Default: True.
ignore_borders (bool) – Remove colonies touching image edges via
clear_border(). Recommended for grid-based colony counting to eliminate partial colonies at plate boundaries. Default: True.
- Returns:
Input image with
objmaskset to binary mask andobjmapset to labeled connected components.- Return type:
Image
- Raises:
ValueError – If threshold computation fails (e.g., degenerate histogram with insufficient intensity variation).
- Best For:
Plates where colony and background pixel counts are roughly balanced.
Medium-contrast images where iterative refinement improves on a single-pass threshold.
Standardised imaging setups where the histogram is approximately symmetric around the threshold.
- Consider Also:
OtsuDetectorfor a faster single-pass threshold when the histogram is clearly bimodal.LiDetectorwhen the histogram is skewed or noise dominates one side of the distribution.HysteresisDetectorwhen colony brightness varies and a single threshold under-segments faint regions.
References
[1] T. W. Ridler and S. Calvard, “Picture thresholding using an iterative selection method,” IEEE Trans. Syst., Man, Cybern., vol. 8, no. 8, pp. 630–632, 1978.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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 = False, ignore_borders: bool = True)[source]
Bases:
ThresholdDetectorDetect colonies by minimising cross-entropy between the original and thresholded image.
Iteratively refine a threshold that minimises the information loss (cross-entropy) between the original intensity distribution and the binarised result. Performs well on low-contrast or noisy plates where the histogram is not clearly bimodal and Otsu’s variance-based assumption does not hold. For a full comparison see Detection Strategies Compared.
- Parameters:
ignore_zeros (bool) – Exclude zero-intensity pixels from threshold computation. Enable for plates with black borders or masked regions; disable only when zero is a meaningful intensity value. Default: True.
ignore_borders (bool) – Remove colonies touching image edges via
clear_border(). Recommended for grid-based colony counting to eliminate partial colonies at plate boundaries. Default: True.
- Returns:
Input image with
objmaskset to binary mask andobjmapset to labeled connected components.- Return type:
Image
- Raises:
ValueError – If threshold computation fails (e.g., degenerate histogram with insufficient intensity variation).
- Best For:
Low-contrast plates where colony and background intensities overlap significantly.
Noisy or textured agar backgrounds that create histogram irregularities breaking bimodal assumptions.
Images where the intensity distribution is unimodal or only weakly bimodal.
- Consider Also:
OtsuDetectorwhen the histogram is clearly bimodal and a fast single-pass threshold suffices.YenDetectorfor a correlation-based alternative that handles skewed histograms.HysteresisDetectorwhen colony brightness varies across the plate and a single threshold under-segments faint regions.
References
[1] C. H. Li and C. K. Lee, “Minimum cross entropy thresholding,” Pattern Recognit., vol. 26, no. 4, pp. 617–625, 1993.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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.MadHysteresisDetector(k_high: float = 5.0, k_low: float = 2.5, min_size: int = 20, connectivity: int = 2, ignore_zeros: bool = False, ignore_borders: bool = True)[source]
Bases:
ThresholdDetectorDetect colonies by MAD-based noise estimation and hysteresis thresholding.
Estimate the background noise floor using the Median Absolute Deviation (MAD), then apply hysteresis thresholding with thresholds set as multiples of the estimated noise standard deviation. Designed for filter response maps (CED, Hessian, LoG, Frangi) where the noise structure is approximately Gaussian and histogram-based methods produce unstable thresholds. For a full comparison see Detection Strategies Compared.
- Parameters:
k_high (float) – High-threshold multiplier. The high threshold is
k_high * sigma_noise; pixels above this seed connected regions. Higher values are more conservative. Typical range: 3.0–8.0. Default: 5.0.k_low (float) – Low-threshold multiplier. The low threshold is
k_low * sigma_noise; pixels above this are included if connected to a high-threshold seed. Must be less thank_high. Typical range: 1.5–4.0. Default: 2.5.min_size (int) – Minimum colony area in pixels. Connected components smaller than this are removed as noise. Default: 20.
connectivity (int) – Pixel connectivity for labelling connected components.
1for 4-connectivity,2for 8-connectivity. Default: 2.ignore_zeros (bool) – Exclude zero-intensity pixels from MAD computation. Enable for plates with black borders or masked regions. Default: True.
ignore_borders (bool) – Remove colonies touching image edges via
clear_border(). Recommended for grid-based colony counting to eliminate partial colonies at plate boundaries. Default: True.
- Returns:
Input image with
objmaskset to binary mask andobjmapset to labeled connected components.- Return type:
Image
- Raises:
ValueError – If
k_low>=k_high.
- Best For:
Filter response maps (CED, Hessian, LoG, Frangi) where the noise floor is approximately Gaussian.
Low-contrast colonies where signal is faint relative to background texture and MAD provides a stable noise estimate.
Standardised pipelines where multiplier-based thresholds generalise across plates with varying colony density.
- Consider Also:
HysteresisDetectorwhen thresholds should be derived from the intensity histogram rather than noise statistics.OtsuDetectorwhen the image is a raw intensity plate with a bimodal histogram.ChanVeseDetectorwhen colonies have diffuse edges and region-based segmentation is more appropriate.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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.ManualDetector(threshold: float = 0.5, ignore_zeros: bool = False, ignore_borders: bool = True)[source]
Bases:
ThresholdDetectorDetect colonies by applying a user-specified intensity threshold.
Apply a fixed intensity cutoff to the plate detection matrix, producing a binary colony mask without any automatic threshold computation. This gives explicit control over detection sensitivity and is the preferred approach when empirical testing has identified an optimal threshold for a specific imaging setup. For a full comparison see Detection Strategies Compared.
- Parameters:
threshold (float) – Intensity cutoff for binary segmentation. Pixels with intensity >= threshold become colony (True), others become background (False). For 8-bit images the valid range is 0–255; for 16-bit images 0–65535; for float images 0.0–1.0. Higher values are more conservative (fewer colonies detected); lower values are more sensitive (more colonies, more noise). Default 0.5. Start by inspecting the image histogram to find the valley between background and colony peaks.
ignore_zeros (bool) – If True (default), exclude zero-intensity pixels from processing. Enable for plates with black borders or masked regions.
ignore_borders (bool) – If True (default), remove colonies touching image edges via
clear_border(). Recommended for grid-based colony counting.
- Returns:
Input image with
objmaskset to a binary colony mask (True = colony, False = background).objmapis not modified.- Return type:
Image
- Raises:
ValueError – If threshold is negative.
- Best For:
Standardised imaging setups where the optimal threshold has been determined empirically and remains stable across plates.
Overriding automatic methods (Otsu, triangle, etc.) that consistently over- or under-segment on a particular plate type.
High-contrast plates where colonies are uniformly bright or dark relative to background and a single cutoff cleanly separates foreground from background.
Reproducibility-critical workflows where a fixed numeric threshold eliminates variability introduced by automatic selection.
- Consider Also:
OtsuDetectorwhen an automatic, parameter-free threshold is preferred and the histogram is bimodal.HysteresisDetectorwhen colony intensity varies across the plate and a single threshold cannot capture all colonies.TriangleDetectorwhen colonies are sparse and the histogram is skewed toward background.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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.ManualGridDetector(coord1: tuple[int, int] = (0, 0), coord2: tuple[int, int] | None = None, shape: Literal['square', 'diamond', 'disk'] = 'disk', width: int = 15)[source]
Bases:
GridObjectDetector,FootprintMixinDetect colonies by stamping footprint masks at evenly-spaced grid positions derived from reference coordinates.
Compute a regular grid of colony positions from one or two user-supplied pixel coordinates, then stamp a morphological footprint at each position to produce
objmaskandobjmap. This purely geometric approach bypasses intensity-based detection entirely, making it ideal when colony positions follow a known pattern but automatic grid detection is unreliable. For a full comparison see Detection Strategies Compared.In one-coordinate mode, coord1 defines the top-left cell centre and symmetric margins are assumed: row spacing =
(H - 2*y) / (nrows - 1), column spacing =(W - 2*x) / (ncols - 1). In two-coordinate mode, coord1 and coord2 define cells (0, 0) and (1, 1); row and column spacing are derived from their difference and extrapolated across all grid cells.- Parameters:
coord1 (tuple[int, int]) –
(y, x)pixel position of the top-left grid cell centre (row 0, column 0). This is the anchor point from which all other positions are calculated. Default(0, 0).coord2 (tuple[int, int] | None) – Optional
(y, x)pixel position of the diagonally adjacent cell (row 1, column 1). When provided, row and column spacing are derived from the difference between coord2 and coord1. When omitted, spacing is computed from image dimensions assuming symmetric margins.shape (Literal['square', 'diamond', 'disk']) – Morphological footprint shape stamped at each grid position.
"disk"(default) preserves round colony geometry."square"covers rectangular well regions."diamond"offers a compromise between the two.width (int) – Diameter of the footprint in pixels (default 15). Larger values cover more area per grid cell; smaller values produce tighter, more precise masks. Typical range: 5–50, depending on image resolution and colony size.
- Returns:
Input image with
objmaskset to the union of all stamped footprints andobjmapset to uniquely labelled regions (1-indexed, row-major order).- Return type:
GridImage
- Raises:
GridImageInputError – If a plain Image is passed instead of a GridImage.
- Best For:
Plates where automatic grid finders fail due to low contrast, missing wells, or non-standard plate formats.
Template-based detection when colony positions are known a priori from plate layout metadata or robotic spotting coordinates.
Generating ground-truth masks for testing or validating other detection pipelines.
Quick prototyping when full detection is unnecessary and grid geometry is well-characterised.
- Consider Also:
RoundPeaksDetectorwhen grid positions can be inferred automatically from intensity profiles.WatershedDetectorwhen colonies are not on a regular grid and must be separated by region growing.InoculumDetectorwhen inoculation sites must be detected from image content rather than geometric templates.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- napari(image: GridImage) ManualGridDetector[source]
Interactively pick 1–2 anchor coordinates using a napari viewer.
Opens a blocking napari viewer displaying the plate image layers (RGB, grayscale, detection matrix). Click up to two points to define the grid anchor positions, then click Confirm in the dock widget. The picked coordinates update coord1 and coord2 on this detector instance.
- Parameters:
image (GridImage) – The GridImage to display for coordinate selection.
- Returns:
Self, for method chaining.
- Return type:
- 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.ManualPointDetector(centers: np.ndarray | list | None = None, shape: Literal['square', 'diamond', 'disk'] = 'disk', width: int = 15)[source]
Bases:
ObjectDetector,FootprintMixinDetect objects by stamping footprint masks at user-specified coordinates.
Place a morphological footprint at each explicitly provided
(y, x)centre coordinate to produceobjmaskandobjmap. UnlikeManualGridDetector, which extrapolates a regular grid from one or two anchor points, this class requires an explicit list of every colony centre. This makes it suitable for plates without regular geometry, sparse or irregular layouts, and manual annotation workflows where each object position is known individually.- Parameters:
centers (np.ndarray | list | None) – An N x 2 array-like of
(y, x)pixel coordinates specifying each colony centre. Accepts any sequence thatnp.asarraycan convert (list of tuples, nested list, or NumPy array). When None or empty,apply()zeros outobjmaskandobjmapand returns immediately.shape (Literal['square', 'diamond', 'disk']) – Morphological footprint shape stamped at each coordinate.
"disk"(default) preserves round colony geometry."square"covers rectangular regions."diamond"offers a compromise between the two.width (int) – Diameter of the footprint in pixels (default 15). Larger values cover more area per colony; smaller values produce tighter, more precise masks. Typical range: 5–50, depending on image resolution and colony size.
- Returns:
Input image with
objmaskset to the union of all stamped footprints andobjmapset to uniquely labelled regions (1-indexed, in the order centres were supplied).- Return type:
Image
- Best For:
Manual annotation and ground-truth mask generation for benchmarking detection algorithms.
Non-grid plates (e.g., streak plates, random inoculations, environmental samples) where colony positions are irregular.
Validating other detection algorithms by comparing their output against user-curated centre coordinates.
Quick prototyping on small numbers of colonies without needing automatic detection.
- Consider Also:
ManualGridDetectorwhen colonies lie on a regular grid and only one or two anchor coordinates are needed.RoundPeaksDetectorwhen colony centres can be inferred automatically from intensity profiles.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- napari(image: Image) ManualPointDetector[source]
Interactively pick colony center coordinates using a napari viewer.
Opens a blocking napari viewer displaying the plate image layers. Click points to mark colony centers, then click Confirm in the dock widget. The picked coordinates are stored in centers.
- Parameters:
image (Image) – The Image to display for coordinate selection.
- Returns:
Self, for method chaining.
- Return type:
- 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 = False, ignore_borders: bool = True)[source]
Bases:
ThresholdDetectorDetect colonies by thresholding at the mean image intensity.
Use the arithmetic mean of all pixel intensities as the threshold, classifying pixels above the mean as colony foreground. This parameter-free baseline is fast and deterministic, making it useful for quick sanity checks or as a fallback when histogram-adaptive methods produce unexpected results. For a full comparison see Detection Strategies Compared.
- Parameters:
ignore_zeros (bool) – Exclude zero-intensity pixels from threshold computation. Enable for plates with black borders or masked regions; disable only when zero is a meaningful intensity value. Default: True.
ignore_borders (bool) – Remove colonies touching image edges via
clear_border(). Recommended for grid-based colony counting to eliminate partial colonies at plate boundaries. Default: True.
- Returns:
Input image with
objmaskset to binary mask andobjmapset to labeled connected components.- Return type:
Image
- Raises:
ValueError – If threshold computation fails (e.g., all pixels share the same intensity value).
- Best For:
Quick baseline detection requiring no parameter tuning.
Sanity-checking preprocessing steps before applying a more specialised detector.
Plates where colony and background areas are roughly equal in size.
Debugging pipelines where a simple, predictable threshold is needed.
- Consider Also:
OtsuDetectorfor a statistically optimal threshold that adapts to the histogram shape.TriangleDetectorwhen colonies are sparse and the histogram is strongly skewed toward background.IsodataDetectorfor an iterative refinement that converges beyond the simple mean.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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 = False, ignore_borders: bool = True)[source]
Bases:
ThresholdDetectorDetect colonies by finding the valley between two histogram peaks.
Locate the intensity minimum (valley) between the two dominant peaks of the image histogram and threshold at that point. This works well when colonies and background form two clearly separated intensity populations, as the valley provides a natural separation boundary. For a full comparison see Detection Strategies Compared.
- Parameters:
ignore_zeros (bool) – Exclude zero-intensity pixels from threshold computation. Enable for plates with black borders or masked regions; disable only when zero is a meaningful intensity value. Default: True.
ignore_borders (bool) – Remove colonies touching image edges via
clear_border(). Recommended for grid-based colony counting to eliminate partial colonies at plate boundaries. Default: True.
- Returns:
Input image with
objmaskset to binary mask andobjmapset to labeled connected components.- Return type:
Image
- Raises:
ValueError – If the histogram has no clear bimodal distribution and no valley can be found.
- Best For:
High-contrast plates where colony and background intensities form two distinct, well-separated histogram peaks.
Standardised imaging setups producing consistently bimodal histograms across plates.
Images where the intensity gap between colonies and agar is wide and the valley is unambiguous.
- Consider Also:
OtsuDetectorwhen the histogram is bimodal but peaks are broad or partially overlapping.LiDetectorwhen the histogram is unimodal or weakly bimodal and a cross-entropy criterion is more appropriate.HysteresisDetectorwhen colony brightness varies and a single valley-based threshold under-segments faint regions.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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 = False, ignore_borders: bool = True)[source]
Bases:
ThresholdDetectorDetect colonies by global Otsu thresholding on bimodal plate histograms.
Automatically compute a single intensity threshold that minimises within-class variance, separating colony foreground from agar background. The resulting binary mask cleanly segments plates whose histograms are bimodal (one peak for background, one for colonies). For a comparison of all available detection strategies see Detection Strategies Compared.
- Parameters:
ignore_zeros (bool) – If True (default), exclude zero-intensity pixels from threshold computation. Enable for plates with black borders or masked regions; disable only when zero is a meaningful intensity value. Typical range: True for most workflows.
ignore_borders (bool) – If True (default), remove colonies touching image edges via
clear_border(). Recommended for grid-based colony counting to eliminate partial colonies at plate boundaries.
- Returns:
Input image with
objmaskset to a binary colony mask produced by Otsu thresholding andobjmapset to labeled connected components.- Return type:
Image
- Raises:
ValueError – If threshold computation fails (e.g., all pixels share the same intensity value, producing a degenerate histogram).
- Best For:
Plates imaged under standardised lighting where the intensity histogram has two well-separated peaks.
Quick baseline detection requiring no parameter tuning.
High-throughput screens with uniform agar colour and colony density.
Comparing automatic methods – Otsu is the standard reference threshold.
Clean plates with minimal dust, scratches, or condensation.
- Consider Also:
TriangleDetectorwhen colonies occupy a small fraction of the plate and the histogram is skewed.HysteresisDetectorwhen colony intensity varies (e.g., young versus mature growth) and a single threshold under-segments.WatershedDetectorwhen touching colonies must be split into individually labelled objects.
References
[1] N. Otsu, “A threshold selection method from gray-level histograms,” IEEE Trans. Syst., Man, Cybern., vol. 9, no. 1, pp. 62–66, 1979.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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.RankOtsuDetector(shape: Literal['square', 'diamond', 'disk'] = 'square', width: int | None = None, ignore_zeros: bool = False)[source]
Bases:
ObjectDetector,FootprintMixinDetect colonies by adaptive local Otsu thresholding within a sliding footprint.
Compute an Otsu threshold independently for every pixel using a local spatial neighbourhood, producing a per-pixel adaptive threshold map. This compensates for vignetting, lighting gradients, and spatially varying agar colour that cause a single global threshold to over- or under-segment parts of the plate. For a full comparison see Detection Strategies Compared.
- Parameters:
shape (Literal['square', 'diamond', 'disk']) – Footprint shape for the local neighbourhood. Accepted values:
'square','diamond','disk'. Disk and diamond are rotationally symmetric; square is faster. Default:'square'.width (int | None) – Footprint width (or radius for disk/diamond) in pixels. If
None, auto-scales tomin(height, width) // 8. Larger values smooth the threshold spatially (less local adaptation); smaller values track finer illumination changes but may over-segment. Default: None.ignore_zeros (bool) – Exclude zero-intensity pixels from the local threshold computation. Enable for plates with black borders or masked regions. Default: False.
- Returns:
Input image with
objmaskset to binary mask andobjmapset to labeled connected components.- Return type:
Image
- Raises:
ValueError – If
shapeis not one of the accepted values orwidthis not positive.
- Best For:
Plates with vignetting, hot-spots, or centre-to-edge illumination gradients.
Large-format plates (384-well or larger) where lighting uniformity is difficult to achieve.
Images with spatially varying agar colour or reflectance.
- Consider Also:
OtsuDetectorwhen illumination is uniform and a fast global threshold suffices.HysteresisDetectorwhen colony brightness varies but spatial illumination is reasonably even.ChanVeseDetectorwhen colonies have diffuse edges and region-based segmentation is more appropriate.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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', 'li'] = 'otsu', subtract_background: bool = True, remove_noise: bool = True, footprint_width: int = 6, noise_radius: int = 1, smoothing_sigma: float = 2.0, min_peak_distance: int | None = None, peak_prominence: float | None = None, edge_refinement: bool = True, selection_mode: Literal['dominant', 'centered', 'regularized'] = 'dominant', split_merged: bool = True)[source]
Bases:
GridInferenceMixin,ObjectDetectorDetect round colonies on gridded plates by row/column peak analysis (gitter algorithm).
Threshold the plate image, project row and column intensity sums to detect periodic peaks, infer grid edges from peak positions, and assign one colony per grid cell. This implements the gitter algorithm optimised for pinned microbial culture plates with circular colonies arranged in regular arrays (96, 384, 1536 formats). For a full comparison see Detection Strategies Compared.
- Parameters:
thresh_method (Literal['otsu', 'mean', 'local', 'triangle', 'minimum', 'isodata', 'li']) – Thresholding method for binary mask creation. Options:
'otsu'(default),'mean','local','triangle','minimum','isodata','li'.'otsu'works well for most standardised imaging setups;'local'adapts to spatial illumination gradients.subtract_background (bool) – If True (default), apply white tophat transform to remove uneven illumination before thresholding. Disable on plates with uniform lighting to save compute time.
remove_noise (bool) – If True (default), apply morphological opening to remove small noise artefacts from the binary mask.
footprint_width (int) – Width in pixels for the background subtraction kernel (default 6). When a GridImage is provided, an adaptive kernel sized to 1.5x colony spacing is used instead, making this a fallback for plain Image inputs. Typical range: 4–20.
noise_radius (int) – Radius of the diamond structuring element for morphological noise removal (default 1, yielding a 3x3 diamond). Increase for larger noise artefacts. Typical range: 1–3.
smoothing_sigma (float) – Gaussian sigma for smoothing row/column intensity profiles before peak detection (default 2.0). Higher values suppress noise but may merge adjacent colony peaks. Set to 0 to disable smoothing. Typical range: 0–5.0.
min_peak_distance (int | None) – Minimum pixel distance between detected peaks. If None (default), automatically estimated from grid dimensions.
peak_prominence (float | None) – Minimum prominence threshold for peak detection. If None (default), auto-calculated as 0.1 * signal range. Higher values are more selective. Typical range: 0.05–0.3 of signal range.
edge_refinement (bool) – If True (default), refine grid edges using weighted local intensity profiles for improved accuracy.
selection_mode (Literal['dominant', 'centered', 'regularized']) – Strategy for choosing one object per grid cell.
"dominant"(default) keeps the largest object by pixel count."centered"keeps the object whose centroid is closest to the cell centre."regularized"fits a global regular-grid model from median row/column centroids, then re-selects per cell – best for pinned arrays.split_merged (bool) – If True (default), pre-split merged colonies that span multiple grid cells using EDT watershed before grid assignment. Set to False when colonies are well-separated and splitting is unnecessary.
- Returns:
Input image with
objmaskset to a binary colony mask andobjmapset to a labelled colony map with one label per grid cell.- Return type:
Image
- Raises:
ValueError – If an invalid thresholding method is specified.
- Best For:
Pinned yeast or bacterial plates with colonies arranged in a regular rectangular grid.
Plates where colony shape is approximately circular and colonies are well-separated or only mildly touching.
High-throughput screens where automatic grid inference eliminates the need for manual grid specification.
Workflows that require one-colony-per-cell assignment for downstream quantification.
- Consider Also:
WatershedDetectorwhen colonies are densely packed and touching but not arranged on a regular grid.FilamentousFungiDetectorwhen colonies exhibit spreading, filamentous growth that violates the round-colony assumption.OtsuDetectorwhen a simple binary mask is sufficient and per-cell assignment is not needed.ManualGridDetectorwhen colony positions are known a priori from robotic spotting coordinates.
References
[1] O. Wagih and L. Parts, “gitter: A robust and accurate method for quantification of colony sizes from plate images,” G3 (Bethesda), vol. 4, no. 3, pp. 547–552, 2014.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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', 'li'] = 'otsu', subtract_background: bool = True, remove_noise: bool = True, footprint_width: int = 6, noise_radius: int = 1, smoothing_sigma: float = 2.0, min_peak_distance: int | None = None, peak_prominence: float | None = None, edge_refinement: bool = True, selection_mode: Literal['dominant', 'centered', 'regularized'] = 'dominant', split_merged: bool = True)[source]
Initialize the RoundPeaksDetector with specified parameters.
- Parameters:
thresh_method (Literal['otsu', 'mean', 'local', 'triangle', 'minimum', 'isodata', 'li']) – Method for thresholding the image. Options are: ‘otsu’ (default), ‘mean’, ‘local’, ‘triangle’, ‘minimum’, ‘isodata’, ‘li’.
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_width (int) – Width in pixels for the background subtraction kernel. When a GridImage is provided, an adaptive kernel sized to 1.5x colony spacing is used instead, making this a fallback.
noise_radius (int) – Radius for the diamond structuring element used in morphological noise removal. Default 1 (3x3 diamond, matching gitter). Increase for larger noise artifacts.
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.
selection_mode (Literal['dominant', 'centered', 'regularized']) – Strategy for choosing one object per grid cell. ‘dominant’ (default) keeps the largest, ‘centered’ keeps the most centred, ‘regularized’ uses a global fit.
split_merged (bool) – If True (default), pre-split merged colonies that span multiple grid cells using EDT watershed before assignment.
- apply(image, inplace=False)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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.SecondaryOtsuDetector(*args, **kwargs)[source]
Bases:
ThresholdDetectorDetect colonies by two-stage Otsu thresholding with per-object refinement.
Apply an initial global Otsu threshold (or reuse an existing
objmask), then re-threshold each detected object independently using its own intensity distribution. This sharpens colony boundaries on plates where colonies vary in brightness, removing soft halos while preserving colony cores. For a full comparison see Detection Strategies Compared.- Returns:
Input image with
objmaskset to binary mask andobjmapset to labeled connected components.- Return type:
Image
- Best For:
Refining boundaries after an initial global threshold that leaves soft or blurry colony edges.
Heterogeneous plates where colonies differ in pigmentation or optical density across the plate surface.
Suppressing preprocessing halos that expand colony outlines beyond their true boundaries.
- Consider Also:
OtsuDetectorwhen a single global threshold already produces clean colony boundaries.HysteresisDetectorwhen colony intensity varies smoothly and dual-threshold expansion is more appropriate than per-object refinement.RankOtsuDetectorwhen spatially varying illumination is the primary cause of boundary inaccuracy.
References
[1] N. Otsu, “A threshold selection method from gray-level histograms,” IEEE Trans. Syst., Man, Cybern., vol. 9, no. 1, pp. 62–66, 1979.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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.SinePeakDetector(thresh_method: Literal['otsu', 'mean', 'local', 'triangle', 'minimum', 'isodata', 'li'] = 'otsu', subtract_background: bool = True, remove_noise: bool = True, footprint_width: int = 6, noise_radius: int = 1, smoothing_sigma: float = 2.0, min_peak_distance: int | None = None, peak_prominence: float | None = None, edge_refinement: bool = True, correlation_threshold: float = 0.3, selection_mode: Literal['dominant', 'centered', 'regularized'] = 'dominant', split_merged: bool = True)[source]
Bases:
GridInferenceMixin,ObjectDetectorDetect colonies on gridded plates using sinusoidal cross-correlation peak finding.
Generate a sinusoidal template matching the expected colony periodicity, compute FFT-based rank (Spearman) cross-correlation against row and column projection signals, and select peaks from the correlation output to locate grid positions. Rank-based correlation is insensitive to outlier colonies and monotonic intensity transformations, making this more robust than direct peak finding on plates with heterogeneous growth. For a full comparison see Detection Strategies Compared.
- Parameters:
thresh_method (Literal['otsu', 'mean', 'local', 'triangle', 'minimum', 'isodata', 'li']) – Thresholding method for binary mask creation. Accepted values:
'otsu','mean','local','triangle','minimum','isodata','li'. Default:'otsu'.subtract_background (bool) – Apply white tophat transform to remove uneven illumination before thresholding. Default: True.
remove_noise (bool) – Apply morphological opening to remove small noise artifacts from the binary mask. Default: True.
footprint_width (int) – Width in pixels for the background subtraction kernel. When a GridImage is provided, an adaptive kernel sized to 1.5x colony spacing is used instead. Default: 6.
noise_radius (int) – Radius of the diamond structuring element for morphological noise removal. Default: 1.
smoothing_sigma (float) – Standard deviation for Gaussian smoothing of row/column intensity profiles before cross-correlation. Higher values smooth noise but may merge adjacent peaks. Set to 0 to disable. Default: 2.0.
min_peak_distance (int | None) – Minimum pixel distance between detected peaks. If
None, automatically estimated from grid dimensions. Default: None.peak_prominence (float | None) – Minimum prominence for peak detection. If
None, auto-calculated as 0.1 * signal range. Higher values are more selective. Default: None.edge_refinement (bool) – Refine grid edges using weighted local intensity profiles for improved accuracy. Default: True.
correlation_threshold (float) – Minimum normalised cross-correlation for a peak to be valid. Lower values accept weaker matches; higher values are more selective. Typical range: 0.1–0.5. Default: 0.3.
selection_mode (Literal['dominant', 'centered', 'regularized']) – Strategy for choosing one object per grid cell.
"dominant"keeps the largest object by pixel count."centered"keeps the object closest to the cell centre."regularized"fits a global regular-grid model from median centroids, then re-selects per cell. Default:"dominant".split_merged (bool) – Pre-split merged colonies spanning multiple grid cells using EDT watershed before grid assignment. Default: True.
- Returns:
Input image with
objmaskset to binary mask andobjmapset to labeled connected components.- Return type:
Image
- Raises:
ValueError – If
thresh_methodis not one of the accepted values.
- Best For:
Gridded plates (96-well, 384-well, pinned arrays) where colonies are arranged in a regular periodic pattern.
Plates with heterogeneous colony sizes or uneven growth where rank-based correlation outperforms intensity-based peak finding.
High-throughput batch processing of arrayed plates without manual grid specification.
- Consider Also:
RoundPeaksDetectorfor a simpler grid detector when colony intensities are uniform and direct peak finding suffices.OtsuDetectorwhen colonies are not gridded and a global threshold is appropriate.RankOtsuDetectorwhen spatial illumination variation is the primary challenge rather than grid localisation.
References
[1] O. Wagih and L. Parts, “gitter: a robust and accurate method for quantification of colony sizes from plate images,” G3 (Bethesda), vol. 4, no. 3, pp. 547–552, 2014.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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', 'li'] = 'otsu', subtract_background: bool = True, remove_noise: bool = True, footprint_width: int = 6, noise_radius: int = 1, smoothing_sigma: float = 2.0, min_peak_distance: int | None = None, peak_prominence: float | None = None, edge_refinement: bool = True, correlation_threshold: float = 0.3, selection_mode: Literal['dominant', 'centered', 'regularized'] = 'dominant', split_merged: bool = True)[source]
Initialize the SinePeakDetector with specified parameters.
- Parameters:
thresh_method (Literal['otsu', 'mean', 'local', 'triangle', 'minimum', 'isodata', 'li']) – Method for thresholding the image. Options are: ‘otsu’ (default), ‘mean’, ‘local’, ‘triangle’, ‘minimum’, ‘isodata’, ‘li’.
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_width (int) – Width in pixels for the background subtraction kernel. When a GridImage is provided, an adaptive kernel sized to 1.5x colony spacing is used instead, making this a fallback.
noise_radius (int) – Radius for the diamond structuring element used in morphological noise removal. Default 1 (3x3 diamond, matching gitter). Increase for larger noise artifacts.
smoothing_sigma (float) – Standard deviation for Gaussian smoothing of intensity profiles before cross-correlation. 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.
correlation_threshold (float) – Minimum normalized cross-correlation value for a peak to be considered valid. Default 0.3. Values below this threshold are zeroed before peak detection.
selection_mode (Literal['dominant', 'centered', 'regularized']) – Strategy for choosing one object per grid cell. ‘dominant’ (default) keeps the largest, ‘centered’ keeps the most centred, ‘regularized’ uses a global fit.
split_merged (bool) – If True (default), pre-split merged colonies that span multiple grid cells using EDT watershed before assignment.
- apply(image, inplace=False)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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(*args, **kwargs)[source]
Bases:
ThresholdDetectorDetect colonies by triangle thresholding on skewed, background-dominant plate histograms.
Compute a threshold at the base of the triangle formed by the histogram peak, minimum, and maximum. This method excels when colonies occupy a small fraction of the plate so that the intensity histogram is strongly skewed toward background. The resulting binary mask captures sparse or faint colonies that Otsu may miss. For a full comparison see Detection Strategies Compared.
- Returns:
Input image with
objmaskset to the thresholded binary mask andobjmapset to labeled connected components.- Return type:
Image
- Raises:
ValueError – If threshold computation fails (e.g., degenerate histogram with insufficient intensity variation).
- Best For:
Plates where colonies are sparse and background dominates the intensity histogram.
Faintly pigmented or translucent colonies that produce a small foreground peak relative to the background tail.
Early time-point images where colony growth is minimal and most pixels belong to the agar background.
Drop-out screens with many empty grid positions and few visible colonies.
- Consider Also:
OtsuDetectorwhen colonies and background occupy roughly equal histogram areas (balanced bimodal distribution).HysteresisDetectorwhen colony brightness varies across the plate and a single threshold under-segments faint regions.ManualDetectorwhen an empirically determined threshold is known to outperform automatic methods for your plate type.
References
[1] G. W. Zack, W. E. Rogers, and S. A. Latt, “Automatic measurement of sister chromatid exchange frequency,” J. Histochem. Cytochem., vol. 25, no. 7, pp. 741–753, 1977.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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 = False)[source]
Bases:
ThresholdDetectorDetect and separate touching colonies by watershed segmentation on a distance-transform surface.
Threshold the plate image to a binary mask, compute a Euclidean distance transform to locate colony centres, seed markers at local maxima, and propagate labelled regions via watershed on the Sobel gradient. This region-growing approach individually labels colonies that are in physical contact – a scenario where global thresholding merges them into a single object. For a full comparison see Detection Strategies Compared.
- Parameters:
footprint (Literal['auto'] | np.ndarray | int | None) – Structuring element for peak detection.
'auto'infers size from grid spacing (GridImage only); an int creates a diamond of that radius; an ndarray supplies a custom footprint; None (default) lets scikit-image choose. Larger footprints merge nearby peaks into fewer seeds; smaller footprints yield finer segmentation. Typical range: 5–50 (diamond radius in pixels).min_size (int) – Minimum object area in pixels (default 50). Objects smaller than this are removed as dust or debris. Typical range: 20–200 depending on image resolution and colony size.
compactness (float) – Watershed compactness parameter (default 0.001). Higher values enforce more regularly shaped segments; lower values let regions follow intensity gradients freely. Typical range: 0.0001–0.1. Increase if colonies are round and over-segmented; decrease for irregular morphologies.
connectivity (int) – Connectivity for region labelling (1 = 4-connected, 2 = 8-connected; default 1). Higher connectivity merges diagonally adjacent pixels.
relabel (bool) – If True (default), relabel segments to consecutive IDs after watershed.
ignore_zeros (bool) – If True (default), exclude zero-intensity pixels from threshold computation. Enable for plates with black borders or masked regions.
- Returns:
Input image with
objmapset to a labelled colony map where each colony receives a unique integer label.objmaskis derived from the non-zero region of the label map.- Return type:
Image
- Raises:
ValueError – If invalid parameters are provided or if the distance transform / watershed computation fails.
- Best For:
Dense plates where colonies touch or overlap and must be counted individually.
Plates with variable colony sizes (e.g., mutant libraries) where the distance transform naturally adapts seed placement.
Irregular colony morphologies that follow local intensity gradients better than geometric assumptions.
Post-incubation plates where colony crowding is the primary segmentation challenge.
- Consider Also:
OtsuDetectorwhen colonies are well-separated and a simple binary mask suffices.RoundPeaksDetectorwhen colonies sit on a regular pinned grid and peak-based assignment is more efficient.FilamentousFungiDetectorwhen colonies exhibit spreading, filamentous growth rather than compact morphology.CannyDetectorwhen edge contrast is stronger than intensity contrast for delineating colony boundaries.
References
[1] S. Beucher and C. Lantuejoul, “Use of watersheds in contour detection,” in Proc. Int. Workshop on Image Processing, CCETT, Rennes, France, 1979.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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 = False, ignore_borders: bool = True)[source]
Bases:
ThresholdDetectorDetect colonies by maximising the correlation between the original and binarised image.
Compute a threshold that maximises the correlation coefficient between the original intensity image and its binarised version. Handles skewed histograms better than Otsu in some scenarios, offering a middle ground between variance-based (Otsu) and entropy-based (Li) criteria. For a full comparison see Detection Strategies Compared.
- Parameters:
ignore_zeros (bool) – Exclude zero-intensity pixels from threshold computation. Enable for plates with black borders or masked regions; disable only when zero is a meaningful intensity value. Default: True.
ignore_borders (bool) – Remove colonies touching image edges via
clear_border(). Recommended for grid-based colony counting to eliminate partial colonies at plate boundaries. Default: True.
- Returns:
Input image with
objmaskset to binary mask andobjmapset to labeled connected components.- Return type:
Image
- Raises:
ValueError – If threshold computation fails (e.g., degenerate histogram with insufficient intensity variation).
- Best For:
High-contrast plates with clear intensity separation between colonies and agar.
Images with skewed histograms where one class is larger than the other.
Exploratory analysis when unsure whether a variance-based or entropy-based criterion fits the data better.
- Consider Also:
OtsuDetectorfor a faster variance-based threshold when the histogram is balanced and bimodal.LiDetectorwhen the histogram is low-contrast or unimodal and entropy-based separation is more appropriate.TriangleDetectorwhen colonies are very sparse and the histogram is strongly background-dominated.
References
[1] J. C. Yen, F. J. Chang, and S. Chang, “A new criterion for automatic multilevel thresholding,” IEEE Trans. Image Process., vol. 4, no. 3, pp. 370–378, 1995.
See also
- Tutorial 2: Detecting Colonies
Step-by-step tutorial for basic colony detection.
- How To: Choose a Detection Algorithm
Guide for selecting the right detector for your plate images.
- Detection Strategies Compared
In-depth comparison of all detection strategies.
- __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)
Detect colonies using sinusoidal cross-correlation grid estimation.
This method performs the core detection workflow: 1. Extract grid dimensions (if GridImage) 2. Threshold the detection matrix with adaptive kernel sizing 3. Remove noise if requested 4. Label connected components 5. Determine or estimate grid edges (via sinusoidal cross-correlation) 6. Assign dominant colonies to grid cells 7. Create final object map
- Parameters:
image – Image object to process. Can be a regular Image or GridImage.
- Returns:
The processed image with updated objmask and objmap.
- Return type:
Image
- 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.