phenotypic.enhance#

Image enhancers to boost fungal colonies on agar backgrounds.

Preprocessing steps that denoise, normalize, and emphasize colony structure before detection. The module covers local contrast equalization (CLAHE), Gaussian/median/rank denoising, rolling-ball and Gaussian background subtraction, tophat and Laplacian edge accentuation, Sobel gradients, contrast stretching, unsharp masking, bilateral denoising, BM3D denoising, Hessian-based ridge detection (Frangi vesselness, Sato tubeness, Meijering neuriteness, Hessian filter) for filamentous structure detection, morphological operations (opening, closing, erosion, dilation, gradient, black tophat) for noise removal and boundary enhancement, and more for clean plates. All operate on copies of the grayscale view to keep raw data intact.

class phenotypic.enhance.AnscombeForward(gain: float = 1.0, mu: float = 0.0, sigma: float = 0.0, scale_factor: float | None = None)[source]#

Bases: ImageEnhancer

Apply the forward Generalized Anscombe Transform for variance stabilization.

Converts Poisson-Gaussian noise into approximately Gaussian noise by applying a variance-stabilizing square-root transformation to detect_mat. After this transform, standard Gaussian denoisers (wavelets, BM3D, bilateral filters) work effectively on the stabilized signal. Always pair with AnscombeInverse in a pipeline, with denoising operations between them; both must use identical parameter values.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • gain (float) – Camera gain in electrons per ADU. Typical range: 0.1–10.0. Default: 1.0.

  • mu (float) – Read noise mean (baseline offset). Typical range: 0.0–50.0. Default: 0.0.

  • sigma (float) – Read noise standard deviation. Set to 0 for pure Poisson noise. Typical range: 0.0–10.0. Default: 0.0.

  • scale_factor (float | None) – Converts normalized [0,1] data to counts. If None (default), auto-detects from image metadata: 255 for 8-bit, 65535 for 16-bit.

Returns:

Input image with detect_mat in variance-stabilized (sqrt-scaled) domain. rgb and gray are unchanged.

Return type:

Image

Raises:

ValueError – If gain <= 0, sigma < 0, or scale_factor <= 0.

Best For:
  • Low-light or fluorescence plate images with photon-counting noise.

  • Images from CCD/CMOS sensors where noise is Poisson-dominated.

  • Enabling Gaussian denoisers on data with signal-dependent noise.

Consider Also:

References

[1] F. J. Anscombe, “The transformation of Poisson, binomial and negative-binomial data,” Biometrika, vol. 35, no. 3/4, pp. 246–254, Dec. 1948.

[2] M. Makitalo and A. Foi, “Optimal inversion of the generalized Anscombe transformation for Poisson-Gaussian noise,” IEEE Trans. Image Process., vol. 22, no. 1, pp. 91–103, Jan. 2013.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of enhancement pipelines on plate images. What Enhancement Actually Does for background on variance-stabilizing transforms and denoising 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__(gain: float = 1.0, mu: float = 0.0, sigma: float = 0.0, scale_factor: float | None = None)[source]#
Parameters:
  • gain (float) – Camera gain in electrons per ADU. Higher gain amplifies both signal and noise. Default 1.0 assumes unity gain.

  • mu (float) – Read noise mean (baseline offset). For calibrated cameras, typically near 0. Default 0.0.

  • sigma (float) – Read noise standard deviation. Set to 0 for pure Poisson noise. Increase for cameras with significant read noise (e.g., 1-5 for CCD sensors). Default 0.0.

  • scale_factor (float | None) – Converts normalized [0,1] data to counts. If None (default), auto-detects from image metadata. Set manually if auto-detection fails or for raw count data (use 1.0).

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.AnscombeInverse(gain: float = 1.0, mu: float = 0.0, sigma: float = 0.0, scale_factor: float | None = None)[source]#

Bases: ImageEnhancer

Apply the inverse Generalized Anscombe Transform to restore original scale.

Converts variance-stabilized data back to the [0, 1] intensity range using the closed-form approximation of the exact unbiased inverse. Always pair with AnscombeForward in a pipeline, placing denoising operations between the forward and inverse transforms. Both must use identical parameter values.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • gain (float) – Camera gain in electrons per ADU. Must match the value used in AnscombeForward. Default: 1.0.

  • mu (float) – Read noise mean (baseline offset). Must match the forward transform. Default: 0.0.

  • sigma (float) – Read noise standard deviation. Must match the forward transform. Default: 0.0.

  • scale_factor (float | None) – Converts counts back to normalized [0,1] range. Must match the forward transform. If None (default), auto-detects from image metadata.

Returns:

Input image with detect_mat restored to [0, 1] intensity range. rgb and gray are unchanged.

Return type:

Image

Raises:

ValueError – If gain <= 0, sigma < 0, or scale_factor <= 0.

Best For:
  • Completing an Anscombe-based denoising pipeline.

  • Restoring biologically meaningful intensities after GAT-domain denoising.

  • Fluorescence or low-light plate workflows that require variance-stabilized processing.

Consider Also:

References

[1] F. J. Anscombe, “The transformation of Poisson, binomial and negative-binomial data,” Biometrika, vol. 35, no. 3/4, pp. 246–254, Dec. 1948.

[2] M. Makitalo and A. Foi, “Optimal inversion of the generalized Anscombe transformation for Poisson-Gaussian noise,” IEEE Trans. Image Process., vol. 22, no. 1, pp. 91–103, Jan. 2013.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of enhancement pipelines on plate images. What Enhancement Actually Does for background on variance-stabilizing transforms and denoising 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__(gain: float = 1.0, mu: float = 0.0, sigma: float = 0.0, scale_factor: float | None = None)[source]#
Parameters:
  • gain (float) – Camera gain in electrons per ADU. Must match the value used in AnscombeForward. Default 1.0.

  • mu (float) – Read noise mean. Must match the value used in AnscombeForward. Default 0.0.

  • sigma (float) – Read noise standard deviation. Must match the value used in AnscombeForward. Default 0.0.

  • scale_factor (float | None) – Converts counts back to normalized [0,1] range. Must match the value used in AnscombeForward. If None (default), auto-detects from image metadata.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.BM3DDenoiser(sigma_psd: float = 0.02, block_size: int = 8, *, stage_arg: Literal['all_stages', 'hard_thresholding'] = 'all_stages', clip: bool = True)[source]#

Bases: ImageEnhancer

Denoise detect_mat with block-matching and 3D collaborative filtering.

Groups similar image patches and filters them jointly in the transform domain, preserving fine colony details while removing structured noise patterns (scanner artifacts, systematic CCD noise, imaging hardware texture). Produces higher-quality results than simple Gaussian blur at significantly higher computational cost.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • sigma_psd (float) – Noise standard deviation in [0, 1] normalized scale. Typical range: 0.01–0.05 for moderate noise, 0.05–0.15 for heavy noise. Too low preserves noise; too high removes colony texture. Default: 0.02.

  • block_size (int) – Block size for BM3D patch matching. Default: 8.

  • stage_arg (Literal['all_stages', 'hard_thresholding']) – Processing mode. 'all_stages' (default) applies both hard thresholding and Wiener filtering for highest quality; 'hard_thresholding' runs only the first stage for faster processing.

  • clip (bool) – Clip output to [0, 1]. Default: True. Set to False when using with variance-stabilizing transforms (e.g., GAT).

Returns:

Input image with detect_mat denoised via BM3D collaborative filtering. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Structured camera or scanner noise on plate images.

  • Low-light imaging where high ISO introduces patterned noise.

  • Preserving fine morphological features (wrinkles, satellite colonies) during denoising.

Consider Also:

References

[1] K. Dabov, A. Foi, V. Katkovnik, and K. Egiazarian, “Image denoising by sparse 3-D transform-domain collaborative filtering,” IEEE Trans. Image Process., vol. 16, no. 8, pp. 2080–2095, Aug. 2007.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of denoising pipelines on plate images. How To: Denoise Low-Light Images for BM3D and other denoising strategies on low-light plate images.

__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_psd: float = 0.02, block_size: int = 8, *, stage_arg: Literal['all_stages', 'hard_thresholding'] = 'all_stages', clip: bool = True)[source]#
Parameters:
  • sigma_psd (float) – Noise level estimate in [0, 1] normalized scale. Start with 0.02-0.05 for typical scanner noise on plates (equivalent to σ=5-12 on 8-bit). Higher value -> more noise.

  • block_size (int) – Block size for BM3D denoising. Default is 8.

  • stage_arg (Literal["all_stages", "hard_thresholding"]) – Denoising stages to run. ‘all_stages’ gives best quality at the cost of speed; ‘hard_thresholding’ is faster and adequate for routine plate analysis.

  • clip (bool) – Whether to clip output to [0, 1] range. Default True. Set to False when using with variance-stabilizing transforms (e.g., GAT) that require preserving the original scale.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.BayesShrinkEnhancer(sigma: float | None = None, wavelet: str = 'db2', mode: Literal['soft', 'hard'] = 'soft', wavelet_levels: int | None = None, clip: bool = True)[source]#

Bases: ImageEnhancer

Denoise detect_mat with adaptive BayesShrink wavelet thresholding.

Applies wavelet-domain denoising with per-subband adaptive thresholds computed from local statistics. Preserves more fine detail than VisuShrinkEnhancer by denoising aggressively only where noise is high and gently where signal dominates.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • sigma (float | None) – Noise standard deviation in [0, 1] scale. None (default) auto-estimates via MAD. Typical range: 0.01–0.05 for moderate scanner/camera noise. Accurate estimation improves adaptive threshold quality.

  • wavelet (str) – Wavelet family. 'db2' (default) balances smoothness and locality; 'db4' preserves finer details. Must be orthogonal.

  • mode (Literal['soft', 'hard']) – Thresholding mode. 'soft' (default) produces smoother results; 'hard' preserves edges more aggressively.

  • wavelet_levels (int | None) – Decomposition depth. None (default) uses max-3 automatically. Higher values allow finer noise/signal separation.

  • clip (bool) – Clip output to [0, 1]. Default: True. Set to False when using with variance-stabilizing transforms (e.g., GAT).

Returns:

Input image with detect_mat denoised via adaptive wavelet thresholding. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Images with spatially varying noise from uneven illumination.

  • Preserving colony texture and internal morphology during denoising.

  • Scanner noise and camera artifacts on plates where fine detail matters for downstream measurement.

  • Pre-filtering before feature extraction or texture analysis.

Consider Also:
  • VisuShrinkEnhancer for faster denoising with a universal threshold when spatial noise uniformity is acceptable.

  • BM3DDenoiser for state-of-the-art denoising of structured noise patterns.

  • BilateralDenoise for edge-preserving smoothing without wavelet decomposition.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of enhancement pipelines on plate images. What Enhancement Actually Does for background on wavelet denoising and threshold selection 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 | None = None, wavelet: str = 'db2', mode: Literal['soft', 'hard'] = 'soft', wavelet_levels: int | None = None, clip: bool = True)[source]#

Initialize BayesShrink adaptive wavelet denoiser.

Parameters:
  • sigma (float | None) – Noise standard deviation in [0, 1] scale. None (default) auto-estimates. More accurate sigma improves adaptive thresholding quality. Typical: 0.01-0.05 for moderate noise.

  • wavelet (str) – Wavelet type. ‘db2’ (default) is general-purpose. ‘db4’ for finer details, ‘sym2’ for symmetric filters.

  • mode (Literal['soft', 'hard']) – ‘soft’ (default) for smoother denoising, ‘hard’ for sharper edges with possible noise residue.

  • wavelet_levels (int | None) – Decomposition depth. None (default) uses max-3. Increase for very noisy images.

  • clip (bool) – Whether to clip output to [0, 1] range. Default True. Set to False when using with variance-stabilizing transforms (e.g., GAT) that require preserving the original scale.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.BilateralDenoise(sigma_color: float | None = None, sigma_spatial: float = 15, *, win_size: int | None = None, mode: str = 'constant', cval: float = 0, clip: bool = True)[source]#

Bases: ImageEnhancer

Denoise detect_mat with edge-preserving bilateral filtering.

Averages pixel values based on both spatial proximity and intensity similarity, preserving sharp colony boundaries while smoothing uniform regions such as agar background. Effectively removes scanner noise, agar grain, dust speckles, and condensation artifacts without blurring colony edges.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • sigma_color (float | None) – Intensity similarity weighting. Small values (0.02–0.05) preserve subtle boundaries; medium values (0.05–0.15) balance denoising and edge preservation; large values (0.2–0.5) smooth aggressively. None (default) auto-estimates from image statistics.

  • sigma_spatial (float) – Spatial distance weighting in pixels. Small values (1–5) apply local denoising; medium values (10–20) smooth regionally; large values (30–50) smooth wide areas. Keep below the minimum colony diameter. Default: 15.

  • win_size (int | None) – Window size for filter computation. None (default) auto-calculates from sigma_spatial.

  • mode (str) – Boundary handling. Accepted values: 'constant', 'edge', 'symmetric', 'reflect', 'wrap'. Default: 'constant'.

  • cval (float) – Fill value when mode='constant'. Default: 0.

  • clip (bool) – Clip output to [0, 1]. Default: True. Set to False when using with variance-stabilizing transforms (e.g., GAT).

Returns:

Input image with detect_mat smoothed by bilateral filtering. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Noisy or grainy agar scans from high-ISO photography or old scanners.

  • Plates with surface condensation, dust speckles, or uneven agar texture.

  • Preprocessing before thresholding when colony edges must remain sharp.

  • Low-quality captures where colony morphology must be preserved.

Consider Also:
  • NonLocalMeansDenoiser for stronger denoising of repetitive textures at higher computational cost.

  • BM3DDenoiser for state-of-the-art structured noise removal.

  • SubtractGaussian when the primary problem is illumination gradients rather than pixel-level noise.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of denoising pipelines on plate images. How To: Denoise Low-Light Images for edge-preserving denoising strategies on low-light plate images.

__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_color: float | None = None, sigma_spatial: float = 15, *, win_size: int | None = None, mode: str = 'constant', cval: float = 0, clip: bool = True)[source]#
Parameters:
  • sigma_color (float | None) – Standard deviation for grayvalue/color similarity. Controls how permissive the filter is when averaging nearby pixels. Small values (0.02–0.05 for float images) enforce strict color matching, preserving edges but leaving more noise. Medium values (0.05–0.15) provide balanced denoising and edge preservation—recommended for most fungal colony imaging. Large values (0.2–0.5) aggressively average across brightness ranges, risking boundary blur. If None (default), automatically estimated from the standard deviation of the image. For uint8 images (0–255), scale values proportionally: 0.05 float corresponds roughly to 13 in uint8 scale. Recommended: leave as None for automatic estimation, or set to 0.08–0.12 for typical colony plates.

  • sigma_spatial (float) – Standard deviation for spatial distance in pixels. Controls the extent of the neighborhood influencing each pixel. Small values (1–5) apply highly local denoising, preserving fine texture. Medium values (10–20) smooth regionally without over-smoothing—suitable for general use. Large values (30–50) smooth broad areas, helpful for correcting illumination variations but risking loss of small colonies or merging of adjacent growth. Recommended: 15 for balanced results; adjust based on colony size (keep smaller than minimum colony diameter).

  • win_size (int | None) – Window size for bilateral filter computation. If None (default), automatically calculated as max(5, 2 * ceil(3 * sigma_spatial) + 1). Generally safe to leave as None; adjust only if you have specific performance or memory constraints.

  • mode (str) – How to handle image boundaries. Options: ‘constant’ (default, pad with cval), ‘edge’ (replicate edge), ‘symmetric’, ‘reflect’, ‘wrap’. ‘constant’ with cval=0 works well for agar plate backgrounds (black edges). ‘reflect’ mirrors edges, useful for non-border regions.

  • cval (float) – Constant fill value for boundaries when mode=’constant’. Default is 0 (black), appropriate for agar backgrounds.

  • clip (bool) – Whether to clip output to [0, 1] range. Default True. Set to False when using with variance-stabilizing transforms (e.g., GAT) that require preserving the original scale of transformed data.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.CLAHE(kernel_size: int | None = None, clip_limit: float = 0.01)[source]#

Bases: ImageEnhancer

Boost local contrast in detect_mat using adaptive histogram equalization.

Divides detect_mat into tiles and equalizes the histogram within each tile, with a clip limit that prevents excessive noise amplification. Faint colonies become more visible and easier to threshold, even when illumination varies across the plate.

For a discussion of contrast enhancement strategies, see What Enhancement Actually Does.

Parameters:
  • kernel_size (int | None) – Tile size for local equalization. Smaller tiles reveal tiny colonies but amplify agar texture; larger tiles produce smoother results. None auto-selects based on image size (typically min(height, width) / 15). Default: None.

  • clip_limit (float) – Maximum local contrast amplification. Typical range: 0.005–0.05. Lower values suppress noise; higher values make faint colonies stand out more. Default: 0.01.

Returns:

Input image with detect_mat contrast-enhanced. rgb and gray are unchanged.

Return type:

Image

Raises:

ValueError – If the detect_mat value range is invalid.

Best For:
  • Plates with faint or translucent colonies that blend into agar.

  • Uneven illumination (vignetting, shadows from plate lids).

  • Pre-conditioning before global thresholding (Otsu, Triangle).

  • Early time-point plates where colonies are barely visible.

Consider Also:
  • ContrastStretching for a simpler global contrast adjustment when illumination is already uniform.

  • HomomorphicFilter when the primary problem is a large-scale illumination gradient rather than local contrast.

  • UnsharpMask when edges need sharpening rather than contrast boosting.

References

[1] S. M. Pizer et al., “Adaptive histogram equalization and its variations,” Computer Vision, Graphics, and Image Processing, vol. 39, no. 3, pp. 355–368, Sep. 1987.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of CLAHE before detection. How To: Enhance Low-Contrast Images for a comparison of contrast enhancement methods.

__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__(kernel_size: int | None = None, clip_limit: float = 0.01)[source]#
Parameters:
  • kernel_size (int | None) – Tile size for adaptive equalization. Smaller tiles enhance very local contrast (revealing tiny colonies) but can amplify agar texture; larger tiles produce smoother, gentler effects. None selects an automatic size based on image dimensions.

  • clip_limit (float) – Maximum local contrast amplification. Lower values reduce noise/halo amplification; higher values make faint colonies stand out more but can emphasize dust or condensation.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.CoherenceEnhancingDiffusion(num_iter: int = 20, sigma: float = 1.5, rho: float | None = None, dt: float = 0.1, *, alpha: float = 0.001, C: float = 99.0)[source]#

Bases: ImageEnhancer

Enhance filamentous structures via anisotropic coherence-enhancing diffusion.

Smooths detect_mat preferentially along coherent structures (lines, ridges, edges) while preserving boundaries perpendicular to them. Uses the structure tensor to estimate local orientation and applies directional diffusion that follows elongated features such as fungal hyphae, streak inoculations, and branching colony morphologies.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • num_iter (int) – Number of diffusion iterations. Typical range: 5–100. Small values (5–10) give subtle enhancement; medium values (15–30) are typical; large values (50–100) provide heavy smoothing. Default: 20.

  • sigma (float) – Noise/derivative scale for Gaussian gradient computation. Match to the width of structures to enhance. Typical range: 0.5–5.0. Default: 1.5.

  • rho (float | None) – Integration scale for structure tensor smoothing. Must be >= sigma. None (default) uses sigma (single-scale mode). Typical values: 2–3x sigma.

  • dt (float) – Time step per iteration. Must satisfy the 2D forward-Euler stability bound (<=0.125). Typical range: 0.05–0.125. Default: 0.1.

  • alpha (float) – Minimum diffusivity (0 < alpha < 1). Small values (0.001) maximize anisotropy; larger values (0.01–0.1) add isotropic smoothing. Default: 0.001.

  • C (float) – Contrast percentile (0 < C <= 100) for the adaptive coherence threshold. Higher values restrict anisotropy to the most coherent structures. Default: 99.

Returns:

Input image with detect_mat smoothed along coherent structures. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Filamentous fungal hyphae (Aspergillus, Penicillium, molds) where branching structures need enhancement.

  • Streak inoculation patterns where colonies grow along lines.

  • Preprocessing before ridge detection (Frangi, Sato, Meijering) to reduce noise without losing tubular structures.

  • Faint elongated features in low-contrast or noisy scans.

Consider Also:
  • BilateralDenoise for isotropic edge-preserving denoising of round colonies without directional features.

  • SatoRidgeFilter for direct ridge detection without a diffusion preprocessing step.

  • MeijeringRidgeFilter for detecting very fine neurite-like filaments.

References

[1] J. Weickert, “Coherence-enhancing diffusion filtering,” Int. J. Comput. Vis., vol. 31, no. 2/3, pp. 111–127, Apr. 1999.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of enhancement pipelines on plate images. What Enhancement Actually Does for background on anisotropic diffusion and structure tensor analysis.

__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__(num_iter: int = 20, sigma: float = 1.5, rho: float | None = None, dt: float = 0.1, *, alpha: float = 0.001, C: float = 99.0)[source]#
Parameters:
  • num_iter (int) – Number of diffusion iterations. Controls the total amount of smoothing applied. Small values (5-10) give subtle enhancement; medium values (15-30) are typical; large values (50-100) provide heavy smoothing. Computational cost scales linearly with iterations. Recommended: 20 for balanced enhancement.

  • sigma (float) – Noise/derivative scale (Gaussian derivative σ). Controls the scale at which image gradients are computed for orientation estimation. Match to the width of structures you want to enhance: ~1.5 for fine hyphae (~3px wide), ~3.0 for coarser structures. Recommended: 1.5.

  • rho (float | None) – Integration scale for structure tensor smoothing. Controls the neighborhood over which gradient products are averaged. Must be >= sigma. When None (default), equals sigma (single-scale mode). Larger values produce smoother orientation fields. Typical: 2-3x sigma.

  • dt (float) – Time step for each diffusion iteration. Must satisfy the 2D forward-Euler stability bound of 1/8 (0.125). Smaller values require more iterations for equivalent smoothing. Recommended: 0.1 for stable, efficient diffusion.

  • alpha (float) – Minimum diffusivity parameter (0 < alpha < 1). Ensures some diffusion even in uniform regions, preventing numerical issues. Small values (0.001) maximize anisotropy; larger values (0.01-0.1) add more isotropic smoothing. Recommended: 0.001 for strong directional bias.

  • C (float) – Contrast percentile for the diffusivity function (0 < C <= 100). The Cth percentile of the coherence histogram (lambda1 - lambda2)^2 from the original image is used as the contrast threshold, adapting to image content. Higher values restrict anisotropy to the most coherent structures. Default: 99.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.ContrastStretching(lower_percentile: int = 2, upper_percentile: int = 98)[source]#

Bases: ImageEnhancer

Stretch the intensity range of detect_mat to fill the full dynamic range.

Rescales pixel values based on lower and upper percentiles, compressing outliers (specular highlights, deep shadows) while expanding the range where colony intensities reside. Simpler and faster than CLAHE, with no local tile artifacts.

Parameters:
  • lower_percentile (int) – Dark clipping point. Pixels below this percentile are mapped to the minimum. Typical range: 1–5. Default: 2.

  • upper_percentile (int) – Bright clipping point. Pixels above this percentile are mapped to the maximum. Typical range: 95–99. Default: 98.

Returns:

Input image with detect_mat rescaled to the full dynamic range. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Plates with narrow histograms (under-exposed or low-contrast).

  • Normalizing exposure across different imaging sessions.

  • Quick preprocessing before global thresholding (Otsu, Triangle).

Consider Also:
  • CLAHE when illumination varies spatially across the plate.

  • HomomorphicFilter when the primary issue is a brightness gradient rather than narrow dynamic range.

See also

How To: Enhance Low-Contrast Images for a comparison of contrast enhancement methods. What Enhancement Actually Does for how enhancement fits into the pipeline model.

__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__(lower_percentile: int = 2, upper_percentile: int = 98)[source]#
Parameters:
  • lower_percentile (int) – Dark clipping point. Increase to suppress deep shadows/edge artifacts; too high may remove meaningful dark background structure. Typical range: 1–5.

  • upper_percentile (int) – Bright clipping point. Decrease to suppress glare/highlights; too low may flatten bright colonies. Typical range: 95–99.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.FrangiVesselness(sigmas: Iterable[float] = (0.5, 1, 1.5), alpha: float = 0.5, beta: float = 0.5, gamma: float | None = None, black_ridges: bool = False)[source]#

Bases: ImageEnhancer

Enhance tubular structures in detect_mat using Hessian-based vesselness filtering.

Computes the Frangi vesselness measure from Hessian matrix eigenvalues at multiple scales, producing a response map that highlights elongated features (hyphae, branches, mycelial networks). The output is a probability-like map (0–1) that typically requires thresholding before detection.

For algorithm details, see The Filamentous Fungi Detection Algorithm.

Parameters:
  • sigmas (Iterable[float]) – Scales (standard deviations) for Hessian computation. Smaller values detect finer structures; larger values detect thicker ones. Span the expected range of hyphal widths in pixels. Default: (0.5, 1, 1.5).

  • alpha (float) – Blobness sensitivity (0–1). Lower is more permissive. Default: 0.5.

  • beta (float) – Structuredness sensitivity (0–1). Lower is more permissive. Default: 0.5.

  • gamma (float) – Background suppression threshold. Larger values suppress low-curvature (flat) regions more aggressively. None uses half of the max Hessian norm. Default: None.

  • black_ridges (bool) – If True, detect dark ridges on bright background. If False, detect bright ridges on dark background. Default: False.

Returns:

Input image with detect_mat set to the vesselness response map. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Filamentous fungi (Neurospora, Aspergillus) with branching hyphae.

  • Thin, elongated structures that global thresholding misses.

  • Interconnected mycelial networks or biofilm structures.

  • Pre-filtering before FilamentousFungiDetector.

Consider Also:

References

[1] A. F. Frangi, W. J. Niessen, K. L. Vincken, and M. A. Viergever, “Multiscale vessel enhancement filtering,” in MICCAI, 1998, pp. 130–137.

See also

Tutorial 10: Detecting Filamentous Fungi for a visual walkthrough of filamentous fungi detection. The Filamentous Fungi Detection Algorithm for the theory behind Hessian-based vesselness filtering.

__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__(sigmas: Iterable[float] = (0.5, 1, 1.5), alpha: float = 0.5, beta: float = 0.5, gamma: float | None = None, black_ridges: bool = False)[source]#
Parameters:
  • sigmas (tuple | list) – Sequence of standard deviations for Gaussian derivatives. Smaller values detect finer features, larger values detect thicker structures. Default (0.5, 1, 1.5).

  • alpha (float) – Vesselness sensitivity to blobness. Lower values are more permissive. Range: 0 to 1. Default 0.5.

  • beta (float) – Vesselness sensitivity to structuredness. Lower values are more permissive. Range: 0 to 1. Default is None which uses half of the max Hessian norm.

  • gamma (float) – Threshold for background suppression. Larger values suppress low-curvature regions more aggressively. Default 15.

  • black_ridges (bool) – If True, detect dark ridges (colonies) on bright background. If False, detect bright ridges on dark background. For agar plates with dark colonies on light background, use True. Default False.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.GaussianBlur(sigma: float = 2.0, *, mode: str = 'reflect', cval=0.0, truncate: float = 4.0)[source]#

Bases: ImageEnhancer

Smooth noise in detect_mat using isotropic Gaussian convolution.

Reduces high-frequency noise, scanner artifacts, and minor agar texture so that downstream thresholding responds to colony signal rather than noise. Colony edges become more coherent at the cost of some spatial sharpness.

For a comparison of denoising approaches, see What Enhancement Actually Does.

Parameters:
  • sigma (float) – Standard deviation of the Gaussian kernel in pixels. Controls blur strength. Typical range: 0.5–5.0. Keep below the smallest colony radius to avoid merging adjacent colonies. Default: 2.0.

  • mode (str) – Boundary handling. Accepted values: 'reflect', 'constant', 'nearest'. Default: 'reflect'.

  • cval – Fill value when mode='constant'. Default: 0.0.

  • truncate (float) – Kernel extent in standard deviations. Rarely needs adjustment. Default: 4.0.

Returns:

Input image with detect_mat smoothed by the Gaussian kernel. rgb and gray are unchanged.

Return type:

Image

Raises:

ValueError – If mode is not one of the accepted values.

Best For:
  • Plates with visible scanner noise or agar granularity.

  • Pre-filtering before edge-based detectors (Sobel, Canny).

  • Quick preprocessing when speed matters more than edge preservation.

Consider Also:
  • MedianFilter when salt-and-pepper noise dominates and edge preservation is important.

  • BilateralDenoise for smoothing within regions while keeping colony boundaries sharp.

  • StableDenoise for highest-quality BM3D denoising on critical experiments.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of enhancement before detection. How To: Denoise Low-Light Images for a comparison of denoising methods.

__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 = 2.0, *, mode: str = 'reflect', cval=0.0, truncate: float = 4.0)[source]#
Parameters:
  • sigma (float) – Blur strength; start near 1–3 for high-resolution scans. Keep below the colony width to avoid merging colonies.

  • mode (str) – Boundary handling. ‘reflect’ is a safe default for plates; ‘constant’ may require setting cval close to background.

  • cval (float) – Constant fill value when mode=’constant’.

  • truncate (float) – Kernel extent in standard deviations. Rarely needs adjustment; larger values slightly widen the effective kernel.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.GrayOpening(shape: Literal['square', 'diamond', 'disk'] = 'square', width: int = 5, n_iter: int = 1)[source]#

Bases: ImageEnhancer, FootprintMixin

Remove small bright artifacts from detect_mat via morphological opening.

Applies erosion followed by dilation with a structuring element, removing bright features smaller than the element while preserving the shape of larger structures. Effectively suppresses dust particles, small noise speckles, and tiny satellite colonies.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • shape (Literal['square', 'diamond', 'disk']) – Structuring element geometry. 'square' (default) preserves edges; 'diamond' is more rounded at diagonals; 'disk' provides uniform circular operations.

  • width (int) – Diameter of the structuring element in pixels. Larger values remove larger features. Typical range: 3–15. Default: 5.

  • n_iter (int) – Number of times to apply the opening. Repeated opening with a small element produces smoother results than a single pass with a larger element. Default: 1.

Returns:

Input image with detect_mat morphologically opened. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Removing dust particles and small bright noise from plate scans.

  • Suppressing tiny satellite colonies that interfere with detection of larger colonies.

  • Smoothing the detection surface before background subtraction.

Consider Also:
  • WhiteTophatEnhance when you want to isolate (not remove) small bright structures.

  • SubtractWhiteTophat for subtracting small bright artifacts while retaining the background.

  • BilateralDenoise for noise reduction that preserves edges without morphological assumptions.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of enhancement pipelines on plate images.

__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__(shape: Literal['square', 'diamond', 'disk'] = 'square', width: int = 5, n_iter: int = 1)[source]#

A kernel configuration class for image processing tasks, particularly suited for applications such as analyzing and processing images of microbe colonies on solid media agar. This class enables the definition of a kernel shape and size, which significantly impacts the morphological operations applied to the image (e.g., filtering, dilation, erosion). Adjusting these parameters can enhance or hinder the detection and analysis of colony boundaries, shapes, and distribution.

Parameters:
  • shape (Literal['square', 'diamond', 'disk'])

  • width (int)

  • n_iter (int)

shape#

The geometric shape of the kernel. This attribute governs the pattern and extent of neighboring pixels involved in the processing operation. Choosing “square” results in a uniform rectangular influence, which may be suitable for isotropic features but could introduce angular artifacts in circular features like microbe colonies. The “diamond” shape provides a more angular neighborhood pattern that helps preserve diagonal structures. On the other hand, “disk” introduces a circular pattern that can align well with colony boundaries and reduce distortions in rounded features.

Type:

Literal[“square”, “diamond”, “disk”]

width#

The size (diameter) of the kernel in pixels. A larger width increases the area of influence during image processing, which can smooth out smaller features like noise but potentially merge closely spaced microbe colonies into larger regions. Smaller values offer finer detail and greater distinction between colonies but may leave noise unprocessed or small artifacts unchanged.

Type:

int

n_iter#

Number of times to apply the opening operation. Repeated opening with a small element produces smoother results than a single pass with a larger element. Default: 1.

Type:

int

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.HessianFilter(sigmas: Iterable[float] = (1, 2, 3), alpha: float = 0.5, beta: float = 0.5, gamma: float = 15, black_ridges: bool = False, mode: str = 'reflect', cval: float = 0)[source]#

Bases: ImageEnhancer

Enhance edges and ridge-like structures via multi-scale Hessian filtering.

Computes eigenvalue-based Hessian responses across multiple scales to highlight colony boundaries, thin filamentous structures, and ridge-like features in detect_mat. Multi-scale analysis makes detection robust across varying colony sizes and morphologies.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • sigmas (Iterable[float]) – Sequence of standard deviations for Gaussian derivatives. Smaller values detect finer edges; larger values detect broader structures. Typical range: (1, 2, 3) to (1, 5). Default: (1, 2, 3).

  • alpha (float) – Sensitivity to plate-like structure deviations. Lower values are more permissive. Typical range: 0.1–1.0. Default: 0.5.

  • beta (float) – Sensitivity to blob-like structure deviations. Lower values are more permissive. Typical range: 0.1–1.0. Default: 0.5.

  • gamma (float) – Background suppression threshold. Larger values suppress low-curvature regions (agar background) more aggressively. Typical range: 10–20. Default: 15.

  • black_ridges (bool) – If True, detect dark ridges on bright background. If False (default), detect bright ridges on dark background.

  • mode (str) – Boundary handling. Accepted values: 'reflect', 'constant', 'nearest', 'mirror', 'wrap'. Default: 'reflect'.

  • cval (float) – Fill value when mode='constant'. Default: 0.

Returns:

Input image with detect_mat replaced by the Hessian ridge response map. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Sharp boundaries between colonies and agar background.

  • Thin or elongated structures (filaments, branching) with poor contrast.

  • Size-invariant colony edge enhancement before thresholding.

  • Textured colonies or biofilms with complex internal structure.

Consider Also:
  • SatoRidgeFilter for continuous tube-like structures where Hessian eigenvalue ratios provide cleaner ridge responses.

  • MeijeringRidgeFilter for very fine neurite-like filaments.

  • LaplaceEnhancer for simpler second-derivative edge detection without multi-scale analysis.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of ridge and edge enhancement on plate images. What Enhancement Actually Does for background on Hessian-based structure detection.

__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__(sigmas: Iterable[float] = (1, 2, 3), alpha: float = 0.5, beta: float = 0.5, gamma: float = 15, black_ridges: bool = False, mode: str = 'reflect', cval: float = 0)[source]#
Parameters:
  • sigmas (tuple | list) – Sequence of standard deviations for Gaussian derivatives. Smaller values detect finer edges, larger values detect thicker structures. Default (1, 2, 3).

  • alpha (float) – Sensitivity to plate-like structure deviations. Lower values are more permissive. Range: 0 to 1. Default 0.5.

  • beta (float) – Sensitivity to blob-like structure deviations. Lower values are more permissive. Range: 0 to 1. Default 0.5.

  • gamma (float) – Threshold for background suppression. Larger values suppress low-curvature regions (agar background) more aggressively. Default 15.

  • black_ridges (bool) – If True, detect dark ridges (colonies) on bright background. If False, detect bright ridges on dark background. For agar plates with dark colonies on light background, use True. Default False.

  • mode (str) – Boundary handling mode (‘reflect’, ‘constant’, ‘nearest’, ‘mirror’, ‘wrap’). Default ‘reflect’.

  • cval (float) – Constant value used if mode=’constant’. Default 0.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.HomomorphicFilter(sigma: float = 200.0, gamma_low: float = 0.5, gamma_high: float = 1.5, eps: float = 1e-06)[source]#

Bases: ImageEnhancer

Correct uneven illumination in detect_mat using frequency-domain filtering.

Separates illumination (low-frequency) and reflectance (high-frequency) components in the log domain, applies differential gains to suppress brightness gradients while boosting colony detail, then returns to the linear domain. Particularly effective for plates with vignetting, scanner lighting bands, or shadow gradients.

For how enhancement fits into the pipeline, see What Enhancement Actually Does.

Parameters:
  • sigma (float) – Gaussian sigma for illumination/reflectance cutoff. Controls the spatial scale of the estimated illumination field. Must be large enough that only the gradient is captured, not individual colonies. Typical range: 40–300 (resolution-dependent). Default: 200.0.

  • gamma_low (float) – Gain for illumination component. Values < 1.0 suppress illumination variation. Typical range: 0.3–0.8. Default: 0.5.

  • gamma_high (float) – Gain for reflectance component. Values > 1.0 enhance colony contrast and surface detail. Typical range: 1.0–2.5. Default: 1.5.

  • eps (float) – Small constant to avoid log(0). Rarely needs adjustment. Default: 1e-6.

Returns:

Input image with detect_mat illumination-corrected and clipped to [0.0, 1.0]. rgb and gray are unchanged.

Return type:

Image

Raises:

ValueError – If sigma is not positive.

Best For:
  • Plates with visible vignetting or radial brightness falloff.

  • Flatbed scanner images with horizontal brightness bands.

  • Uneven agar thickness causing variable background brightness.

  • Pre-conditioning before global thresholding on unevenly lit plates.

Consider Also:
  • SubtractGaussian for a simpler spatial-domain background subtraction when the gradient is smooth.

  • CLAHE when the problem is local contrast rather than large-scale illumination.

  • SubtractRollingBall for morphological background estimation.

See also

How To: Enhance Low-Contrast Images for a comparison of contrast and illumination correction methods.

__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 = 200.0, gamma_low: float = 0.5, gamma_high: float = 1.5, eps: float = 1e-06)[source]#
Parameters:
  • sigma (float) – Gaussian sigma for the illumination/reflectance cutoff. Larger values capture broader illumination gradients. Start with a value several times the largest colony diameter.

  • gamma_low (float) – Gain for low frequencies (illumination). < 1 suppresses illumination variation; 1.0 leaves it unchanged.

  • gamma_high (float) – Gain for high frequencies (reflectance). > 1 enhances colony detail; 1.0 leaves it unchanged.

  • eps (float) – Offset to avoid log(0). Rarely needs adjustment.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.ImageInverter[source]#

Bases: ImageEnhancer

Invert detect_mat pixel intensities (negate brightness).

Reverses the brightness scale so dark regions become bright and vice versa. For uint8 data the inversion is 255 - pixel; for floating-point data it is max_value - pixel. Use this when detectors expect colonies as bright regions but the source image has colonies as dark regions.

For algorithm details, see What Enhancement Actually Does.

Returns:

Input image with detect_mat intensity-inverted. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Correcting inverted scan output from imaging systems that produce dark-on-bright colony images.

  • Preprocessing before detectors that expect bright colonies on dark backgrounds.

  • Plates where colony boundaries are defined by dark edges on a bright background.

Consider Also:
  • SetDetectMode when switching the detection channel (e.g., to red or green) would resolve the contrast issue.

  • UnsharpMask when the issue is low contrast rather than inverted polarity.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of enhancement pipelines on plate images.

__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__()[source]#

Initialize the ImageInverter with no parameters.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.LaplaceEnhancer(kernel_size: int | None = 3, mask: numpy.ndarray | None = None)[source]#

Bases: ImageEnhancer

Enhance colony edges in detect_mat with a Laplacian operator.

Applies a discrete Laplacian that responds to rapid intensity changes, highlighting colony margins and ring-like features such as swarming fronts. Useful as a preprocessing step for contour detection, watershed seeding, or separating touching colonies.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • kernel_size (Optional[int]) – Size of the Laplacian kernel. Smaller values (3) capture fine edges but amplify noise; larger values (5–7) smooth noise and emphasize broader boundaries. Default: 3.

  • mask (Optional[np.ndarray]) – Boolean or 0/1 mask to restrict processing to regions of interest (e.g., the circular plate area). None (default) processes the full image.

Returns:

Input image with detect_mat replaced by the Laplacian edge response. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Emphasizing colony edges before edge-based segmentation.

  • Detecting ring patterns around colonies for swarming phenotyping.

  • Generating watershed seeds by highlighting boundary regions.

Consider Also:
  • HessianFilter for multi-scale edge and ridge detection with more tuning control.

  • UnsharpMask for edge enhancement that retains the original intensity profile.

  • PhaseCongruencyEnhancer for contrast-invariant edge detection under uneven illumination.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of edge enhancement on plate images.

__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__(kernel_size: int | None = 3, mask: numpy.ndarray | None = None)[source]#
Parameters:
  • kernel_size (Optional[int]) – Controls the edge scale. Smaller values pick up fine edges but increase noise sensitivity; larger values smooth noise and emphasize broader boundaries.

  • mask (Optional[np.ndarray]) – Boolean/0-1 mask to limit processing to regions of interest (e.g., the circular plate), reducing artifacts from dish rims or labels.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.MedianFilter(mode: Literal['nearest', 'reflect', 'constant', 'mirror', 'wrap'] = 'nearest', shape: Literal['disk', 'square', 'diamond'] | None = None, width: int = 5, cval: float = 0.0)[source]#

Bases: ImageEnhancer

Remove impulsive noise from detect_mat while preserving colony edges.

Replaces each pixel with the median of its local neighborhood, making it robust to outlier pixels (condensation droplets, dust specks, sensor noise). Preserves colony boundaries better than Gaussian smoothing because it does not average across edges.

Parameters:
  • mode (Literal['nearest', 'reflect', 'constant', 'mirror', 'wrap']) – Boundary handling. Accepted values: 'nearest', 'reflect', 'constant', 'mirror', 'wrap'. Default: 'nearest'.

  • shape (Literal['disk', 'square', 'diamond'] | None) – Structuring element shape. Accepted values: 'disk', 'square', 'diamond', or None for library default. Default: None.

  • width (int) – Size of the structuring element in pixels. Larger values smooth more aggressively. Typical range: 3–9. Default: 5.

  • cval (float) – Fill value when mode='constant'. Default: 0.0.

Returns:

Input image with detect_mat filtered. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Plates with salt-and-pepper noise or bright/dark speckle artifacts.

  • Preserving sharp colony edges during denoising.

  • Pre-filtering before edge-based detection (Canny, Sobel).

Consider Also:
  • GaussianBlur for faster, simpler smoothing when edge preservation is less critical.

  • BilateralDenoise for edge-preserving smoothing with continuous intensity gradients.

  • RankMedianEnhancer for configurable rank-based filtering with explicit footprint control.

See also

How To: Denoise Low-Light Images for a comparison of denoising methods on low-light plates. What Enhancement Actually Does for how enhancement fits into the pipeline model.

__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__(mode: Literal['nearest', 'reflect', 'constant', 'mirror', 'wrap'] = 'nearest', shape: Literal['disk', 'square', 'diamond'] | None = None, width: int = 5, cval: float = 0.0)[source]#

This class is designed to facilitate image processing tasks, particularly for analyzing microbe colonies on solid media agar. By adjusting the mode, shape, width, and cval attributes, users can modify the processing behavior and results to suit their specific requirements for studying spatial arrangements, colony boundaries, and other morphological features.

Parameters:
  • mode (Literal['nearest', 'reflect', 'constant', 'mirror', 'wrap'])

  • shape (Literal['disk', 'square', 'diamond'] | None)

  • width (int)

  • cval (float)

mode#

Determines how boundaries of the image are handled during processing. For instance, “reflect” can help minimize edge artifacts when analyzing colonies near the edge of the image by mirroring boundary pixels, while “constant” fills with a value (cval), which might highlight isolated colonies. Adjusting this can significantly affect how edge regions are interpreted.

Type:

Literal[“nearest”, “reflect”, “constant”, “mirror”, “wrap”]

shape#

Specifies the shape of the structuring element used in morphological operations. For instance, “disk” simulates circular neighborhood which works well for circular colonies, whereas “square” gives a grid-like neighborhood. This can directly impact how structures are identified or segmented.

Type:

Literal[“disk”, “square”, “diamond”] | None

width#

Size of the structuring element. Larger widths result in broader neighborhoods being considered, which may smooth or connect distant colonies, while smaller widths preserve finer details but may miss larger structural relationships. Only if shape is not None.

Type:

int

cval#

Value used to fill borders when mode is set to “constant”. This directly affects colony recognition at the edges; for example, setting a high cval compared to colony intensity might obscure colonies near the borders.

Type:

float

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.MeijeringRidgeFilter(sigmas: Iterable[float] = (1, 2, 3), alpha: float | None = None, black_ridges: bool = False, mode: str = 'reflect', cval: float = 0)[source]#

Bases: ImageEnhancer

Enhance fine ridge-like structures in detect_mat with the Meijering neuriteness filter.

Computes the Meijering neuriteness measure from Hessian matrix eigenvalues to highlight elongated, thread-like structures such as delicate filaments, thin wrinkles, and network-like features. More selective than SatoRidgeFilter for very fine, well-separated ridges.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • sigmas (Iterable[float]) – Sequence of standard deviations for Gaussian derivatives. Smaller values detect finer structures; larger values detect thicker features. Typical range: (1, 2, 3) to range(1, 10). Default: (1, 2, 3).

  • alpha (Optional[float]) – Shape parameter controlling linearity sensitivity. None (default) uses -1/(ndim+1) which is -1/3 for 2D images. Rarely requires manual tuning.

  • black_ridges (bool) – If True, detect dark ridges on bright background. If False (default), detect bright ridges on dark background.

  • mode (str) – Boundary handling. Accepted values: 'constant', 'reflect', 'wrap', 'nearest', 'mirror'. Default: 'reflect'.

  • cval (float) – Fill value when mode='constant'. Default: 0.

Returns:

Input image with detect_mat replaced by the Meijering neuriteness response map. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Delicate filamentous structures too thin for standard detection (actinomycetes, fungal hyphae, bacterial networks).

  • Fine wrinkles, grooves, or network features in biofilms.

  • Sparse mycelial networks or bacterial filaments that require sensitive ridge detection.

Consider Also:
  • SatoRidgeFilter for thicker, continuous tubular structures with less sensitivity to parameter tuning.

  • HessianFilter for combined edge and ridge detection with blob sensitivity control.

  • CoherenceEnhancingDiffusion for enhancing directional structures via anisotropic smoothing before ridge detection.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of ridge enhancement on plate images. What Enhancement Actually Does for background on Hessian-based ridge detection methods.

__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__(sigmas: Iterable[float] = (1, 2, 3), alpha: float | None = None, black_ridges: bool = False, mode: str = 'reflect', cval: float = 0)[source]#
Parameters:
  • sigmas (tuple | list) – Sequence of standard deviations for Gaussian derivatives. Smaller values detect finer features, larger values detect thicker structures. Default (1, 2, 3).

  • alpha (float | None) – Shape parameter controlling linearity sensitivity. Default None uses -1/(ndim+1), which for 2D images is -1/3. Unlikely to require manual tuning in practice.

  • black_ridges (bool) – If True, detect dark ridges (colonies) on bright background. If False, detect bright ridges on dark background. For agar plates with dark colonies on light background, use True. Default False.

  • mode (str) – How to handle image boundaries. Options: ‘constant’ (pad with cval), ‘reflect’ (mirror), ‘wrap’ (tile), ‘nearest’ (replicate edge), ‘mirror’ (symmetric mirror). Default ‘reflect’.

  • cval (float) – Fill value when mode=’constant’. Default 0.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.MultiscaleLoGEnhancer(min_radius: float = 3.0, max_radius: float = 12.0, num_scales: int = 12)[source]#

Bases: ImageEnhancer

Enhance blob-like colonies in detect_mat with scale-normalised Laplacian of Gaussian.

Applies LoG filtering across a geometric series of Gaussian sigmas and returns the maximum response at each pixel. Bright blob-like structures (colonies, inocula, droplets) produce strong peaks regardless of size, making this a robust preprocessing step before thresholding or GMM-based segmentation.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • min_radius (float) – Smallest target blob radius in pixels. Blobs smaller than this produce weaker responses. Typical range: 1.0–5.0 at 512x768 resolution. Scale proportionally for higher resolutions. Default: 3.0.

  • max_radius (float) – Largest target blob radius in pixels. Blobs larger than this also produce weaker responses. Typical range: 8.0–50.0 at 512x768 resolution. Default: 12.0.

  • num_scales (int) – Number of logarithmically spaced sigma values. More scales improve size discrimination at higher compute cost. Typical range: 4–20. Default: 12.

Returns:

Input image with detect_mat replaced by the scale-normalised LoG response map. rgb and gray are unchanged.

Return type:

Image

Raises:

ValueError – If min_radius <= 0, min_radius >= max_radius, or num_scales < 1.

Best For:
  • Mixed-size colonies on mature plates where small emerging and large mature colonies must both be detected.

  • Sparse inoculation spots that are faint and nearly invisible against the agar background.

  • Low-contrast or shadowed regions where LoG emphasizes blob structure over absolute intensity.

  • Preprocessing before thresholding to sharpen blob boundaries and suppress uneven illumination.

Consider Also:
  • SatoRidgeFilter for elongated or filamentous structures where LoG’s isotropic assumption is a poor fit.

  • LaplaceEnhancer for simpler single-scale edge detection.

  • SubtractGaussian when the primary issue is illumination gradients rather than blob enhancement.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of blob enhancement on plate images. What Enhancement Actually Does for background on scale-space blob detection and LoG theory.

__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_radius: float = 3.0, max_radius: float = 12.0, num_scales: int = 12)[source]#

Initialize MultiscaleLoGEnhancer with radius range and scale density.

Parameters:
  • min_radius (float) – Smallest target blob radius in pixels. The corresponding Gaussian sigma is min_radius / sqrt(2). Blobs smaller than this radius produce weaker LoG responses. Typical range: 1.0–5.0 pixels at 512×768 resolution. Default: 3.0.

  • max_radius (float) – Largest target blob radius in pixels. The corresponding Gaussian sigma is max_radius / sqrt(2). Blobs larger than this radius also produce weaker responses. Typical range: 8.0–50.0 pixels at 512×768 resolution. Default: 12.0.

  • num_scales (int) – Number of logarithmically spaced sigma values between min_radius / sqrt(2) and max_radius / sqrt(2). Controls size-discrimination resolution. Larger values give finer blob size resolution but increase computation (one LoG evaluation per scale). Typical range: 4–20. Default: 12.

Raises:

ValueError – If min_radius <= 0, min_radius >= max_radius, or num_scales < 1.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.NonLocalMeansDenoiser(patch_size: int = 5, search_dist: int = 11, h: float = 0.5, *, fast_mode: bool = False, sigma: float = 0.0)[source]#

Bases: ImageEnhancer

Denoise detect_mat with non-local means patch-based filtering.

Compares patches across the image to identify similar structures and averages them, preserving thin colony boundaries and internal texture better than simple Gaussian or median filtering. Particularly effective at removing Gaussian noise and agar granularity.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • patch_size (int) – Size of patches used for comparison in pixels. Larger patches capture more structure but are slower. Typical range: 5–15. Default: 5.

  • search_dist (int) – Maximum search distance for similar patches in pixels. Larger values find more candidates at higher cost. Typical range: 5–21. Default: 11.

  • h (float) – Cut-off distance controlling smoothness. Rule of thumb: h ~= noise level (sigma). Higher values produce more smoothing. Default: 0.5.

  • fast_mode (bool) – If True, use faster variant with uniform spatial weighting. If False (default), use original algorithm with Gaussian spatial weighting.

  • sigma (float) – Expected noise standard deviation. Values > 0 improve patch weighting by accounting for expected noise variance. Default: 0.0 (disabled).

Returns:

Input image with detect_mat denoised via non-local means filtering. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Scanner noise and agar granularity where colony edges must stay sharp.

  • Low-contrast or faint colonies where Gaussian blur would cause loss of detail.

  • Preserving colony texture and morphology during speckle and dust removal.

  • Pre-filtering before edge detection to avoid amplifying noise.

Consider Also:
  • BM3DDenoiser for state-of-the-art structured noise removal at higher computational cost.

  • BilateralDenoise for faster edge-preserving denoising without patch comparison.

  • BayesShrinkEnhancer for adaptive wavelet denoising with spatially varying thresholds.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of denoising pipelines on plate images. How To: Denoise Low-Light Images for non-local means and other denoising strategies on low-light plate images.

__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__(patch_size: int = 5, search_dist: int = 11, h: float = 0.5, *, fast_mode: bool = False, sigma: float = 0.0)[source]#
Parameters:
  • patch_size (int) – Size of patches used for comparison. Larger patches capture more structure but are slower. Start with 5-7 for agar plates; increase to 11-15 for heavily noisy images. Default: 7.

  • search_dist (int) – Maximal distance in pixels to search for similar patches. Larger values find more candidates at higher cost. Default: 11.

  • h (float) – Cut-off distance controlling smoothness. Typical rule of thumb: h ≈ sigma (noise level). Increase to ~1.5*sigma for more smoothing. Default: 0.1.

  • fast_mode (bool) – If True, use faster variant with uniform spatial weighting. If False, use original algorithm with Gaussian spatial weighting (slower but potentially better quality). Default: False.

  • sigma (float) – Noise standard deviation. If provided (> 0), improves patch weighting by accounting for expected noise variance. Start with estimate_sigma() output. Default: 0.0 (disabled).

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.OpeningSubtractBg(shape: Literal['square', 'diamond', 'disk'] = 'disk', width: int = 51, n_iter: int = 1)[source]#

Bases: ImageEnhancer, FootprintMixin

Subtract background from detect_mat via OpenCV-accelerated morphological opening.

Computes the white top-hat transform (original minus morphological opening) using OpenCV’s C++/SIMD backend, isolating bright foreground structures smaller than the structuring element while removing slow-varying background intensity. Significantly faster than scikit-image equivalents for high-throughput workflows.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • shape (Literal['square', 'diamond', 'disk']) – Structuring element geometry. 'disk' (default) gives isotropic removal suited to round colonies; 'square' is fastest; 'diamond' is a compromise.

  • width (int) – Diameter of the structuring element in pixels. Must be larger than colony diameter to avoid subtracting colony signal. Typical range: 31–101. Default: 51.

  • n_iter (int) – Number of morphological iterations. Higher values intensify background removal. Default: 1.

Returns:

Input image with detect_mat containing only foreground structures smaller than the structuring element. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Fast background subtraction for high-throughput plate screening.

  • Removing uneven illumination gradients and agar shading before colony detection.

  • Pipelines where speed matters (large batches, parameter sweeps).

  • Drop-in performance upgrade over SubtractRollingBall when a flat structuring element is acceptable.

Consider Also:
  • SubtractRollingBall for parabolic background estimation that handles gradual intensity ramps more accurately.

  • SubtractGaussian for Gaussian-based background subtraction with continuous control over the background scale.

  • WhiteTophatEnhance when you want to keep only the extracted small bright structures.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of background subtraction on plate images. What Enhancement Actually Does for background on morphological background removal 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)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.PhaseCongruencyEnhancer(n_scale: int = 4, n_orient: int = 6, min_wavelength: float = 3.0, mult: float = 2.1, sigma_onf: float = 0.55, k: float = 2.0, cutoff: float = 0.5, g: float = 10.0, noise_method: float = -1, output: Literal['M', 'm', 'pc_sum'] = 'pc_sum')[source]#

Bases: ImageEnhancer

Enhance colony edges in detect_mat with contrast-invariant phase congruency.

Detects features where Fourier components are maximally in phase, regardless of amplitude. This makes the response invariant to image contrast and illumination changes, making it ideal for plates with uneven lighting, scanner vignetting, or varying colony opacity.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • n_scale (int) – Number of wavelet scales. Typical range: 3–6. More scales capture a wider range of feature sizes. Default: 4.

  • n_orient (int) – Number of filter orientations. 6 gives 30-degree angular spacing. Default: 6.

  • min_wavelength (float) – Wavelength of smallest scale filter in pixels. Match to minimum expected colony edge width. Default: 3.0.

  • mult (float) – Scaling factor between successive wavelengths. Controls spectral overlap. Default: 2.1.

  • sigma_onf (float) – Log-Gabor bandwidth parameter. 0.55 gives ~2 octave bandwidth; 0.75 gives ~1 octave. Default: 0.55.

  • k (float) – Noise threshold multiplier. Higher values (5–20) increase noise rejection but may miss faint edges. Default: 2.0.

  • cutoff (float) – Frequency spread penalty threshold. Default: 0.5.

  • g (float) – Sigmoid sharpness for frequency spread weighting. Default: 10.

  • noise_method (float) – Noise estimation method. -1 (default) uses median-based estimation; -2 uses mode-based (Rayleigh); values >= 0 set a fixed noise threshold.

  • output (Literal['M', 'm', 'pc_sum']) – Result to store in detect_mat. 'pc_sum' (default) for scalar phase congruency, 'M' for edge strength, 'm' for corner strength.

Returns:

Input image with detect_mat replaced by the phase congruency map (clipped to [0, 1]). rgb and gray are unchanged.

Return type:

Image

Best For:
  • Colony boundaries independent of colony color or opacity.

  • Images with uneven illumination or scanner vignetting.

  • Faint colony edges that gradient-based methods miss.

  • Translucent or low-contrast colonies on agar.

Consider Also:
  • LaplaceEnhancer for simpler edge detection when illumination is uniform.

  • HessianFilter for multi-scale ridge and edge detection with blob sensitivity control.

  • UnsharpMask for edge sharpening that preserves the original intensity profile.

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 3: Enhancing Before Detection for a visual walkthrough of contrast-invariant enhancement on plate images. What Enhancement Actually Does for background on phase congruency and the Local Energy Model.

__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__(n_scale: int = 4, n_orient: int = 6, min_wavelength: float = 3.0, mult: float = 2.1, sigma_onf: float = 0.55, k: float = 2.0, cutoff: float = 0.5, g: float = 10.0, noise_method: float = -1, output: Literal['M', 'm', 'pc_sum'] = 'pc_sum')[source]#

Initialize phase congruency enhancer.

Parameters:
  • n_scale (int) – Number of wavelet scales. Range [3, 6] typical.

  • n_orient (int) – Number of filter orientations. 6 gives 30 degree spacing.

  • min_wavelength (float) – Wavelength of smallest scale filter in pixels. Should match minimum expected feature width (default 3.0).

  • mult (float) – Scaling factor between successive filter wavelengths. Controls spectral overlap between scales (default 2.1).

  • sigma_onf (float) – Ratio of Gaussian standard deviation to filter center frequency. Controls filter bandwidth. 0.55 gives ~2 octave bandwidth; 0.75 gives ~1 octave (default 0.55).

  • k (float) – Number of noise standard deviations for threshold. Higher values increase noise rejection (default 2.0, range [2, 20]).

  • cutoff (float) – Frequency spread measure below which PC values are penalized (default 0.5).

  • g (float) – Sharpness of sigmoid transition for frequency spread weighting (default 10.0).

  • noise_method (float) – Method for noise statistics estimation. -1 uses median of smallest scale responses (default), -2 uses mode (Rayleigh), values >= 0 are used as fixed noise threshold.

  • output (Literal['M', 'm', 'pc_sum']) – Which result to store in detect_mat. “pc_sum” for scalar phase congruency (default), “M” for edge strength, “m” for corners.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.RankMedianEnhancer(shape: str = 'square', width: int | None = None, shift_x=0, shift_y=0)[source]#

Bases: ImageEnhancer

Suppress impulsive noise in detect_mat with rank-based median filtering.

Applies a local median using rank filters with a configurable structuring element shape and size. Effectively removes salt-and-pepper noise, dust speckles, and pixel-level artifacts while preserving colony boundaries when the footprint is smaller than the minimum colony diameter.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • shape (str) – Footprint geometry. 'disk' for isotropic smoothing; 'square' (default) to align with grid artifacts.

  • width (int) – Footprint width in pixels. Set smaller than the minimum colony diameter to preserve colony edges. None (default) derives a small value from image size.

  • shift_x – Horizontal footprint offset. Typically 0. Default: 0.

  • shift_y – Vertical footprint offset. Typically 0. Default: 0.

Returns:

Input image with detect_mat median-filtered. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Salt-and-pepper or impulsive noise from sensor defects.

  • Dust speckles and pixel-level artifacts on scanned plates.

  • Grid-like imaging artifacts when using a 'square' footprint.

Consider Also:
  • BilateralDenoise for edge-preserving Gaussian noise removal without the intensity quantization of rank filters.

  • NonLocalMeansDenoiser for patch-based denoising that preserves texture better on noisy plates.

  • GrayOpening for morphological artifact removal that does not require uint8 conversion.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of denoising pipelines on plate images.

__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__(shape: str = 'square', width: int | None = None, shift_x=0, shift_y=0)[source]#
Parameters:
  • shape (str) – Geometry of the neighborhood. Use ‘disk’ for isotropic smoothing on plates; ‘square’ to align with grid noise; ‘sphere’/’cube’ for 3D contexts. Default ‘square’.

  • width (int | None) – Neighborhood width in pixels. Set smaller than the minimum colony width to preserve colony edges; None chooses a small default based on image size.

  • shift_x (int) – Horizontal offset of the shape center to bias the neighborhood if artifacts are directional. Typically 0.

  • shift_y (int) – Vertical offset of the shape center. Typically 0.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.SatoRidgeFilter(sigmas: Iterable[float] = (1, 2, 3), black_ridges: bool = False, mode: str = 'reflect', cval: float = 0)[source]#

Bases: ImageEnhancer

Enhance tubular and ridge-like structures in detect_mat with the Sato tubeness filter.

Computes the Sato tubeness measure from Hessian matrix eigenvalues to highlight continuous ridge structures such as filamentous colonies, mycelial networks, and branching morphologies. Less sensitive to parameter tuning than Frangi, making it a good first choice for ridge detection.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • sigmas (Iterable[float]) – Sequence of standard deviations for Gaussian derivatives. Smaller values detect finer structures; larger values detect thicker features. Typical range: (1, 2, 3) to range(1, 10, 2). Default: (1, 2, 3).

  • black_ridges (bool) – If True, detect dark ridges on bright background. If False (default), detect bright ridges on dark background.

  • mode (str) – Boundary handling. Accepted values: 'constant', 'reflect', 'wrap', 'nearest', 'mirror'. Default: 'reflect'.

  • cval (float) – Fill value when mode='constant'. Default: 0.

Returns:

Input image with detect_mat replaced by the Sato tubeness response map. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Thin filamentous colonies or mycelial networks (fungi, Bacillus, streptomycetes).

  • Continuous ridge-like structures that global thresholding misses.

  • Interconnected fungal networks or biofilm structures.

  • Organisms with branching or root-like colony morphologies.

Consider Also:

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of ridge enhancement on plate images. What Enhancement Actually Does for background on Hessian-based ridge detection methods.

__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__(sigmas: Iterable[float] = (1, 2, 3), black_ridges: bool = False, mode: str = 'reflect', cval: float = 0)[source]#
Parameters:
  • sigmas (tuple | list) – Sequence of standard deviations for Gaussian derivatives. Smaller values detect finer features, larger values detect thicker structures. Default (1, 2, 3).

  • black_ridges (bool) – If True, detect dark ridges (colonies) on bright background. If False, detect bright ridges on dark background. For agar plates with dark colonies on light background, use True. Default False.

  • mode (str) – How to handle image boundaries. Options: ‘constant’ (pad with cval), ‘reflect’ (mirror), ‘wrap’ (tile), ‘nearest’ (replicate edge), ‘mirror’ (symmetric mirror). Default ‘reflect’.

  • cval (float) – Fill value when mode=’constant’. Default 0.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.SetDetectMode(mode: Literal['gray', 'red', 'green', 'blue', 'MinRGB', 'LabL', 'LabA', 'LabB', 'HsvS', 'HsvV', 'InvS'] = 'gray')[source]#

Bases: ImageOperation

Switch the detection matrix source channel mid-pipeline.

Resets detect_mat to a fresh copy of the chosen channel, discarding any enhancements applied so far. Useful when different pipeline stages need to operate on different color channels.

For algorithm details, see What Enhancement Actually Does.

Parameters:

mode (DetectMode) – Channel to use for the detection matrix. Accepted values: 'gray' (default), 'red', 'green', 'blue', 'min_rgb'.

Returns:

Input image with detect_mode and detect_mat updated to the chosen channel.

Return type:

Image

Best For:
  • Switching to a specific color channel (e.g., red) that provides better colony-background contrast.

  • Resetting enhancements mid-pipeline to start fresh on a different channel.

  • Plates where colonies are more visible in a single color channel than in grayscale.

Consider Also:
  • ImageInverter when the issue is inverted polarity rather than channel selection.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of channel selection 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: Image, inplace=False) Image#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.SobelFilter(*args, **kwargs)[source]#

Bases: ImageEnhancer

Highlight colony edges in detect_mat using the Sobel gradient operator.

Computes the gradient magnitude to emphasize intensity transitions at colony boundaries. The output is an edge-strength map, not a corrected image — useful as a preprocessing step before watershed seeds or contour-based detectors.

Returns:

Input image with detect_mat set to gradient magnitude. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Pre-filtering before watershed or contour-based detection.

  • Separating touching colonies when combined with marker-based segmentation.

  • Visualizing colony boundary sharpness for quality assessment.

Consider Also:
  • UnsharpMask when you want to sharpen edges without converting to a pure edge map.

  • LaplaceEnhancer for second-derivative edge detection that responds to ridges and valleys.

See also

What Enhancement Actually Does for how edge enhancement fits into the pipeline model.

__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)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.SubtractGaussian(sigma: float = 50.0, mode: str = 'reflect', cval: float = 0.0, truncate: float = 4.0, preserve_range: bool = True, n_iter: int = 1)[source]#

Bases: ImageEnhancer

Remove background from detect_mat by subtracting a Gaussian-blurred estimate.

Estimates a smooth background via Gaussian blur and subtracts it, removing gradual illumination gradients (vignetting, agar thickness, scanner shading) while retaining sharp colony features. Improves downstream thresholding and edge detection.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • sigma (float) – Gaussian standard deviation defining the background scale. Must be larger than the typical colony diameter. Typical range: 20–100. Default: 50.0.

  • mode (str) – Border handling. Accepted values: 'reflect' (default), 'constant', 'nearest', 'mirror', 'wrap'.

  • cval (float) – Fill value when mode='constant'. Default: 0.0.

  • truncate (float) – Gaussian support in standard deviations. Default: 4.0.

  • preserve_range (bool) – Preserve the input value range during filtering. Default: True.

  • n_iter (int) – Number of successive subtraction passes. Multiple passes remove residual background from complex gradients. Typical range: 1–3. Default: 1.

Returns:

Input image with detect_mat background-subtracted and clipped to [0, 1]. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Correcting uneven lighting across plates or scan beds.

  • Flattening background to enhance dark colonies on bright agar.

  • Normalizing batches captured with varying exposure or illumination profiles.

Consider Also:
  • SubtractRollingBall for parabolic background estimation that adapts to non-Gaussian intensity ramps.

  • OpeningSubtractBg for faster morphological background subtraction in high-throughput pipelines.

  • BilateralDenoise when the primary issue is noise rather than illumination gradients.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of background subtraction on plate images. What Enhancement Actually Does for background on illumination correction 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 = 50.0, mode: str = 'reflect', cval: float = 0.0, truncate: float = 4.0, preserve_range: bool = True, n_iter: int = 1)[source]#
Parameters:
  • sigma (float) – Background scale. Set larger than colony diameter so colonies are preserved while slow illumination is removed.

  • mode (str) – Border handling; ‘reflect’ reduces artificial rims on plates.

  • cval (float) – Fill value when mode=’constant’.

  • truncate (float) – Gaussian support in standard deviations (advanced).

  • preserve_range (bool) – Keep the original intensity range; useful if subsequent steps or measurements assume a specific scaling.

  • n_iter (int) – Number of successive subtraction passes. Must be >= 1. One pass (default) removes a single background estimate. Multiple passes (2+) iteratively subtract residual background, useful for complex or multi-scale illumination gradients.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.SubtractRollingBall(radius: int = 100, kernel: numpy.ndarray | None = None, nansafe: bool = False)[source]#

Bases: ImageEnhancer

Remove background from detect_mat with ImageJ-style rolling-ball subtraction.

Models the background as the surface traced by rolling a parabolic ball under the image intensity landscape, then subtracts it. Effectively removes slow illumination gradients and agar shading while preserving colony structures. Handles non-Gaussian intensity ramps better than SubtractGaussian.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • radius (int) – Rolling-ball radius in pixels. Must be larger than the typical colony diameter to avoid subtracting colony signal. Typical range: 50–200. Default: 100.

  • kernel (np.ndarray) – Optional custom ball/shape array. When provided, overrides radius. Default: None.

  • nansafe (bool) – If True, treat NaNs as missing data to avoid artifacts when using masked images. Default: False.

Returns:

Input image with detect_mat background-subtracted. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Scanner vignetting, lid glare, or agar thickness variations.

  • Flattening backgrounds to improve segmentation of dark colonies on bright agar.

  • Images with non-linear illumination gradients where Gaussian subtraction leaves residual background.

Consider Also:
  • SubtractGaussian for faster Gaussian-based subtraction with continuous sigma control.

  • OpeningSubtractBg for OpenCV-accelerated morphological background removal in high-throughput pipelines.

  • WhiteTophatEnhance when you want to isolate small bright structures rather than subtract background.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of background subtraction on plate images. What Enhancement Actually Does for background on rolling-ball and other illumination correction 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__(radius: int = 100, kernel: numpy.ndarray | None = None, nansafe: bool = False)[source]#
Parameters:
  • radius (int) – Rolling-ball width (pixels). Use a value larger than colony diameter to avoid removing colony signal. Default 100.

  • kernel (np.ndarray) – Optional custom ball/shape; when provided it overrides width.

  • nansafe (bool) – If True, treat NaNs as missing data to avoid artifacts when using masked images (e.g., outside the plate).

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.SubtractWhiteTophat(shape: str = 'diamond', width: int | None = None)[source]#

Bases: ImageEnhancer

Suppress small bright artifacts in detect_mat by subtracting the white top-hat.

Computes the white top-hat (original minus morphological opening) and subtracts it from the image, removing small bright blobs such as dust specks, glare highlights, and condensation artifacts while preserving larger colony structures.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • shape (str) – Footprint geometry. 'diamond' (default) or 'disk' provide isotropic behavior; 'square' can align with sensor grid artifacts.

  • width (int) – Maximum bright-object size (pixels) targeted for removal. Set slightly smaller than the smallest colonies to preserve them. None (default) derives a small value from image dimensions.

Returns:

Input image with detect_mat smoothed by subtracting the white top-hat. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Removing small bright artifacts that could be mistaken for tiny colonies.

  • Reducing glare highlights on shiny plates before thresholding.

  • Cleaning up dust and condensation artifacts that confuse detection.

Consider Also:
  • WhiteTophatEnhance when you want to isolate (not suppress) small bright structures.

  • GrayOpening for morphological smoothing that removes small bright features without explicit subtraction.

  • RankMedianEnhancer for impulsive noise removal via median filtering.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of artifact removal on plate images.

__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__(shape: str = 'diamond', width: int | None = None)[source]#
Parameters:
  • shape (str) – Footprint geometry controlling which bright features are removed. ‘diamond’ or ‘disk’ provide isotropic behavior on plates; ‘square’ can align with sensor grid artifacts. Advanced: ‘sphere’ or ‘cube’ for volumetric data.

  • width (int | None) – Maximum bright-object width (in pixels) targeted for removal. Set slightly smaller than the smallest colonies to avoid suppressing real colonies. None picks a small default based on image dimensions.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.UnsharpMask(radius: float = 2.0, amount: float = 1.0, preserve_range: bool = False, n_iter: int = 1)[source]#

Bases: ImageEnhancer

Sharpen colony edges in detect_mat with unsharp masking.

Subtracts a Gaussian-blurred copy from the original and scales the difference to emphasize high-contrast boundaries. Makes soft or indistinct colony edges more pronounced, improving thresholding and edge-detection accuracy.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • radius (float) – Standard deviation of the Gaussian blur in pixels. Controls the scale of features enhanced. Small values (0.5–2.0) sharpen fine details; larger values (5–15) enhance broader features. Default: 2.0.

  • amount (float) – Multiplier for the sharpening effect. Low values (0.3–0.7) produce subtle enhancement; standard values (1.0–1.5) give moderate sharpening; high values (2.0+) create aggressive enhancement with risk of halo artifacts. Default: 1.0.

  • preserve_range (bool) – Preserve the original pixel value range. Default: False.

  • n_iter (int) – Number of successive sharpening passes. Multiple passes compound the effect. Typical range: 1–3. Default: 1.

Returns:

Input image with detect_mat sharpened via unsharp masking. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Low-contrast colonies with soft, gradual edges (translucent growth).

  • Dense plates where colonies blend into background.

  • Pre-threshold sharpening to improve segmentation accuracy.

  • Slight scanner or lens blur that softens colony boundaries.

Consider Also:
  • BilateralDenoise for denoising before sharpening on grainy images to avoid amplifying noise.

  • LaplaceEnhancer for second-derivative edge detection that replaces rather than enhances the intensity profile.

  • PhaseCongruencyEnhancer for contrast-invariant edge detection under uneven illumination.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of edge sharpening on plate images. What Enhancement Actually Does for background on unsharp masking and sharpening 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__(radius: float = 2.0, amount: float = 1.0, preserve_range: bool = False, n_iter: int = 1)[source]#
Parameters:
  • radius (float) – Standard deviation (sigma) of the Gaussian blur in pixels. Defines the scale of features to enhance. Small values (0.5–2) sharpen fine details (thin colony edges, small morphologies); larger values (5–15) enhance broad features (large colonies, colony-background separation). Must be > 0. For fungal colonies, keep below the typical colony width to avoid merging adjacent colonies. Recommended: 2.0–3.0 for general-purpose use, 1.0 for high-density plates, 5.0+ for emphasizing large-scale features on low-resolution images.

  • amount (float) – Amplification factor for the sharpening effect. Controls how much the edge enhancement contributes to the output. Typical range: 0.3–2.5. Low values (0.3–0.7) produce subtle enhancement suitable for noisy images; standard values (1.0–1.5) give balanced sharpening; high values (2.0+) create aggressive enhancement for very low-contrast colonies. Can be negative to produce blurring instead. Excessive amounts risk visible artifacts and noise amplification.

  • preserve_range (bool) – If False (default), output may be rescaled if necessary. If True, the original range of input values is preserved. Keep as False for consistency with other enhancers.

  • n_iter (int) – Number of successive unsharp mask passes to apply. Must be >= 1. One pass (default) applies the filter once. Multiple passes (2+) compound the sharpening effect for progressively more aggressive enhancement, but at increased risk of noise amplification and halo artifacts.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.VisuShrinkEnhancer(sigma: float | None = None, wavelet: str = 'db2', mode: Literal['soft', 'hard'] = 'soft', wavelet_levels: int | None = None, clip: bool = True)[source]#

Bases: ImageEnhancer

Denoise detect_mat with universal VisuShrink wavelet thresholding.

Applies wavelet-domain denoising with a single universal threshold across all subbands, designed to remove all Gaussian noise with high probability. Faster than BayesShrinkEnhancer but may over-smooth regions with low noise. Preserves colony edges better than Gaussian blur.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • sigma (float | None) – Noise standard deviation in [0, 1] scale. None (default) auto-estimates via MAD. Typical range: 0.01–0.05 for moderate scanner/camera noise. Too high causes over-smoothing.

  • wavelet (str) – Wavelet family. 'db2' (default) balances smoothness and locality; 'db4' captures more detail. Must be orthogonal.

  • mode (Literal['soft', 'hard']) – Thresholding mode. 'soft' (default) produces smoother results for additive noise; 'hard' preserves edges more.

  • wavelet_levels (int | None) – Decomposition depth. None (default) uses max-3 automatically. Higher values give finer denoising.

  • clip (bool) – Clip output to [0, 1]. Default: True. Set to False when using with variance-stabilizing transforms (e.g., GAT).

Returns:

Input image with detect_mat denoised via universal wavelet thresholding. rgb and gray are unchanged.

Return type:

Image

Best For:
  • Scanner banding and flatbed scanner noise removal.

  • High-ISO camera images where colony boundaries must remain sharp.

  • Agar granularity and condensation speckle suppression before detection.

  • Pre-filtering before edge detection to avoid noise amplification.

Consider Also:
  • BayesShrinkEnhancer for adaptive thresholding that preserves more detail in regions with varying noise levels.

  • BM3DDenoiser for state-of-the-art structured noise removal at higher computational cost.

  • BilateralDenoise for edge-preserving smoothing without wavelet decomposition.

References

[1] D. L. Donoho and I. M. Johnstone, “Ideal spatial adaptation by wavelet shrinkage,” Biometrika, vol. 81, no. 3, pp. 425–455, Sep. 1994.

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of denoising pipelines on plate images. What Enhancement Actually Does for background on wavelet denoising and threshold selection 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 | None = None, wavelet: str = 'db2', mode: Literal['soft', 'hard'] = 'soft', wavelet_levels: int | None = None, clip: bool = True)[source]#

Initialize VisuShrink wavelet denoiser.

Parameters:
  • sigma (float | None) – Noise standard deviation in [0, 1] scale. None (default) auto-estimates via median absolute deviation (MAD). For reference: 8-bit noise σ=10/255 ≈ 0.04 in normalized scale. Typical values: 0.01-0.05 for moderate scanner/camera noise. Start with auto-estimation, then tune if needed.

  • wavelet (str) – Wavelet type from PyWavelets. ‘db2’ (default) is a good general choice. ‘db4’ for more detail, ‘sym2’ for symmetry. Must be orthogonal (db*, sym*) for proper noise handling.

  • mode (Literal['soft', 'hard']) – Threshold type. ‘soft’ (default) produces smoother results for additive noise. ‘hard’ preserves edges more but may leave noise artifacts.

  • wavelet_levels (int | None) – Decomposition depth. None (default) uses max-3 automatically. Higher = finer denoising, slower.

  • clip (bool) – Whether to clip output to [0, 1] range. Default True. Set to False when using with variance-stabilizing transforms (e.g., GAT) that require preserving the original scale.

apply(image, inplace=False)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.enhance.WhiteTophatEnhance(shape: str = 'disk', width: int | None = None)[source]#

Bases: ImageEnhancer

Isolate small bright structures in detect_mat with the white top-hat transform.

Computes the white top-hat (original minus morphological opening) and retains the result, extracting bright features smaller than the structuring element while suppressing larger background structures. Highlights small bright colonies, inocula, or specks against uneven illumination.

For algorithm details, see What Enhancement Actually Does.

Parameters:
  • shape (str) – Footprint geometry. 'disk' (default) preserves rounded colony shapes; 'diamond' is computationally efficient; 'square' can align with sensor grid artifacts.

  • width (int) – Maximum bright-object size (pixels) targeted for extraction. Set slightly larger than the maximum size of colonies you want to isolate. None (default) derives a small value from image dimensions.

Returns:

Input image with detect_mat containing only the extracted small bright structures. rgb and gray are unchanged.

Return type:

Image

Raises:

ValueError – If an unsupported footprint shape is provided.

Best For:
  • Isolating small bright colonies from larger background structures.

  • Highlighting faint small colonies against uneven illumination.

  • Extracting tiny bright specks for detection or quantification.

  • Preprocessing before detecting small colony phenotypes.

Consider Also:

See also

Tutorial 3: Enhancing Before Detection for a visual walkthrough of morphological enhancement on plate images.

__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)#

Applies the operation to an image, either in-place or on a copy.

Parameters:
  • image (Image) – The arr image to apply the operation on.

  • inplace (bool) – If True, modifies the image in place; otherwise, operates on a copy of the image.

Returns:

The modified image after applying the operation.

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.