phenotypic.prefab.RoundPeaksPipeline#

class phenotypic.prefab.RoundPeaksPipeline(*, blur_sigma: int = 5, blur_mode: str = 'reflect', blur_cval: float = 0.0, blur_truncate: float = 4.0, detector_thresh_method: Literal['otsu', 'mean', 'local', 'triangle', 'minimum', 'isodata'] = 'otsu', detector_subtract_background: bool = True, detector_remove_noise: bool = True, detector_footprint_radius: int = 5, detector_smoothing_sigma: float = 2.0, detector_min_peak_distance: int | None = None, detector_peak_prominence: float | None = None, detector_edge_refinement: bool = True, texture_scale: int | List[int] = 5, texture_quant_lvl: Literal[8, 16, 32, 64] = 32, texture_enhance: bool = False, texture_warn: bool = False, benchmark: bool = False, verbose: bool = False)[source]#

Bases: PrefabPipeline

Lightweight pipeline for circular colonies on solid media agar.

This prefab pipeline provides a streamlined sequence of operations tailored for imaging pinned or arrayed fungal colonies on solid media agar. It performs a gentle Gaussian blur to suppress scanner and agar noise, followed by a grid-aware circular colony detector and a compact set of measurement modules. Compared with HeavyRoundPeaksPipeline, this variant exposes a smaller number of stages and parameters but still allows fine control over blur strength, thresholding, grid refinement, and texture scale.

Operations:
  1. GaussianBlur

  2. RoundPeaksDetector

Measurements:
  • MeasureShape

  • MeasureIntensity

  • MeasureTexture

  • MeasureColor

Parameters#

blur_sigmaint, optional

Standard deviation (in pixels) of the Gaussian blur kernel. Lower values preserve sharp edges and small colonies, which is useful when pins produce tight colonies with fine boundaries. Higher values smooth away scanner grain and agar micro-texture but can merge neighboring colonies or wash out tiny satellite growth.

blur_mode{“reflect”, “constant”, “nearest”}, optional

Boundary handling strategy for the blur. "reflect" (default) mirrors intensities at the plate edge and avoids artificial halos, which is helpful for colonies close to the border of an agar image. "constant" and "nearest" can be used for cropped regions but may introduce rim artifacts that slightly bias edge intensity and downstream detection.

blur_cvalfloat, optional

Constant fill value used when blur_mode="constant". Setting this close to the background agar intensity can stabilize blur at cut edges of the plate. A value too bright or too dark may create spurious rims that either look like faint colonies or mask real colonies near the image boundary.

blur_truncatefloat, optional

Radius of the Gaussian kernel in standard deviations. Increasing this slightly widens the effective blur footprint and further smooths broad illumination gradients on the plate, at the cost of speed. For typical pinned fungal colonies, the default is usually sufficient; very large values can over-smooth diffuse halos or ring-like growth.

detector_thresh_method{“otsu”, “mean”, “local”, “triangle”, “minimum”, “isodata”}, optional

Thresholding method used inside RoundPeaksDetector. "otsu" works well for plates with reasonably uniform agar and clear contrast between colonies and background. "local" can cope with strong gradients or condensation streaks but may be slower. "mean", "triangle", "minimum", and "isodata" offer alternative trade-offs and can be useful when colonies are very pale or when agar pigmentation varies strongly across the plate.

detector_subtract_backgroundbool, optional

Whether to normalize background intensity before thresholding. Enabling this (default) helps make colonies more comparable across plates with different agar batches or scanner settings. If disabled, very faint colonies on bright agar may be missed, but native shading patterns or radial nutrient gradients remain more faithful.

detector_remove_noisebool, optional

Whether to remove small specks using a morphological opening before grid inference. This is often beneficial for fungal plates with dust, bubbles, or condensation droplets, but if colonies are extremely small (early time points or slow-growing strains) an aggressive noise removal may erase real colonies.

detector_footprint_radiusint, optional

Radius in pixels used for morphological operations in the detector. Larger values clean up bigger spurious regions and slightly shrink detected colonies. For tightly pinned arrays, too large a radius can erode narrow colonies or disconnect wispy hyphal fronts, under- estimating colony size.

detector_smoothing_sigmafloat, optional

Standard deviation of the 1D Gaussian smoothing used when estimating row/column intensity profiles for grid detection. Increasing this makes grid inference more robust to noisy or streaky agar images but may blur subtle deviations in grid regularity (e.g., warped pinning patterns) so that mispinned colonies are forced into a regular grid.

detector_min_peak_distanceint or None, optional

Minimum allowed distance between inferred grid lines (peaks). When set explicitly, this constrains the expected spacing between pinned colony rows/columns, helping reject spurious peaks caused by glare or edge artifacts. If None (default), the distance is estimated from the data, which is more flexible but can be unstable for plates with many missing colonies.

detector_peak_prominencefloat or None, optional

Minimum prominence required for peaks in the row/column profiles. Higher values make the detector ignore weak structures such as barely growing colonies or diffuse halos, focusing instead on strong, dense colonies. Lower values are more sensitive to early growth but can be confused by agar texture or illumination bands.

detector_edge_refinementbool, optional

If True, refines estimated grid edges using local intensity profiles. This improves alignment of each pinned colony to its grid cell, especially when colonies expand asymmetrically or when the plate is slightly shifted during imaging. Disabling refinement speeds up analysis but may misplace colonies at the edge of their wells.

texture_scaleint or list[int], optional

Spatial scale(s) in pixels at which texture is measured by MeasureTexture. Smaller values emphasize fine-scale surface roughness (e.g., wrinkling or concentric ring patterns on filamentous colonies). Larger values summarize broader patterns such as coarse colony zoning or radial banding. Using multiple scales (by passing a list) increases feature richness but also computation time.

texture_quant_lvl{8, 16, 32, 64}, optional

Intensity quantization level for texture computation. Higher values capture subtler differences in pigmentation and surface texture but require more data and are more sensitive to noise. For images of fungal colonies with smooth agar backgrounds, 32 is a good balance; 8 or 16 may be preferable for very low-contrast plates.

texture_enhancebool, optional

If True, enhances contrast before measuring texture. This can make faint radial structures or sectoring within colonies more detectable, which is useful when subtle phenotypes matter. However, enhancement may exaggerate scanner artifacts or agar imperfections, so enabling it can bias texture metrics on marginal images.

texture_warnbool, optional

If True, emits warnings when texture measurements may be unreliable (for example, very small colonies or extreme intensity clipping). This can help identify pins where scanner saturation, agar contamination, or segmentation artifacts distort morphology.

benchmarkbool, optional

If True, records timing information for each pipeline stage. This is primarily useful when optimizing throughput for large plate series but adds minor overhead.

verbosebool, optional

If True, logs additional information during pipeline execution. This can help debug unexpected detection behavior (e.g., missing rows of colonies) or confirm that grid inference behaves sensibly on new imaging setups.

Notes#

This pipeline is intended for relatively clean, well-aligned images of pinned or arrayed circular colonies on agar where only a modest amount of preprocessing is needed. For plates with severe background gradients, strong vignetting, or highly irregular grids, consider using HeavyRoundPeaksPipeline, which exposes additional refinement and alignment stages.

Methods

__init__

This class represents a processing and measurement abc_ for Image operations and feature extraction.

apply

The class provides an abc_ to process and apply a series of operations on an Image.

apply_and_measure

Applies processing to the given image and measures the results.

benchmark_results

Returns a table of execution times for operations and measurements.

dispose_widgets

Drop references to the UI widgets.

from_json

Deserialize a pipeline from JSON format.

measure

Measures properties of a given image and optionally includes metadata.

set_meas

Sets the measurements to be used for further computation.

set_ops

Sets the operations to be performed.

sync_widgets_from_state

Push internal state into widgets.

to_json

Serialize the pipeline configuration to JSON format.

widget

Return (and optionally display) the root widget.

__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: bool = False, reset: bool = True) GridImage | Image#

The class provides an abc_ to process and apply a series of operations on an Image. The operations are maintained in a queue and executed sequentially when applied to the given Image.

Parameters:
  • image (Image) – The arr Image to be processed. The type Image refers to an instance of the Image object to which transformations are applied.

  • inplace (bool, optional) – A flag indicating whether to apply the transformations directly on the provided Image (True) or create a copy of the Image before performing transformations (False). Defaults to False.

  • reset (bool) – Whether to reset the image before applying the pipeline

Return type:

Union[GridImage, Image]

apply_and_measure(image: Image, inplace: bool = False, reset: bool = True, include_metadata: bool = True) pd.DataFrame#

Applies processing to the given image and measures the results.

This function first applies a processing method to the supplied image, adjusting it based on the given parameters. After processing, the resulting image is measured, and a DataFrame containing the measurement data is returned.

Parameters:
  • image (Image) – The image to process and measure.

  • inplace (bool) – Whether to modify the original image directly or work on a copy. Default is False.

  • reset (bool) – Whether to reset any previous processing on the image before applying the current method. Default is True.

  • include_metadata (bool) – Whether to include metadata in the measurement results. Default is True.

Returns:

A DataFrame containing measurement data for the processed image.

Return type:

pd.DataFrame

benchmark_results() pandas.DataFrame#

Returns a table of execution times for operations and measurements.

This method should be called after applying the pipeline on an image to get the execution times of the different processes.

Returns:

A DataFrame containing execution times for each operation and measurement.

Return type:

pd.DataFrame

dispose_widgets() None#

Drop references to the UI widgets.

Return type:

None

classmethod from_json(json_data: str | Path) SerializablePipeline#

Deserialize a pipeline from JSON format.

This method reconstructs a pipeline from a JSON string or file, restoring all operations, measurements, and configuration flags. Classes are imported from the phenotypic namespace and instantiated with their saved parameters.

Parameters:

json_data (str | Path) – Either a JSON string or a path to a JSON file.

Returns:

A new pipeline instance with the loaded configuration.

Return type:

SerializablePipeline

Raises:
  • ValueError – If the JSON is invalid or cannot be parsed.

  • ImportError – If a required operation or measurement class cannot be imported.

  • AttributeError – If a class cannot be found in the phenotypic namespace.

Example

Deserialize a pipeline from JSON format
>>> from phenotypic import ImagePipeline
>>>
>>> # Load from file
>>> pipe = ImagePipeline.from_json('my_pipeline.json')
>>>
>>> # Load from string
>>> json_str = '{"ops": {...}, "meas": {...}}'
>>> pipe = ImagePipeline.from_json(json_str)
measure(image: Image, include_metadata=True) pd.DataFrame#

Measures properties of a given image and optionally includes metadata. The method performs measurements using a set of predefined measurement operations. If benchmarking is enabled, the execution time of each measurement is recorded. When verbose mode is active, detailed logging of the measurement process is displayed. A progress bar is used to track progress if the tqdm library is available.

Parameters:
  • image (Image) – The image object for which measurements are performed. It must support the info method and optionally a grid or objects attribute.

  • include_metadata (bool, optional) – Indicates whether metadata should be included in the measurements. Defaults to True.

Returns:

A DataFrame containing the results of all performed measurements combined

on the same index.

Return type:

pd.DataFrame

Raises:

Exception – An exception is raised if a measurement operation fails while being applied to the image.

set_meas(measurements: List[MeasureFeatures] | Dict[str, MeasureFeatures])#

Sets the measurements to be used for further computation. The input can be either a list of MeasureFeatures objects or a dictionary with string keys and MeasureFeatures objects as values.

The method processes the given input to construct a dictionary mapping measurement names to MeasureFeatures instances. If a list is passed, unique class names of the MeasureFeatures instances in the list are used as keys.

Parameters:

measurements (List[MeasureFeatures] | Dict[str, MeasureFeatures]) – A collection of measurement features either as a list of MeasureFeatures objects, where class names are used as keys for dictionary creation, or as a dictionary where keys are predefined strings and values are MeasureFeatures objects.

Raises:

TypeError – If the measurements argument is neither a list nor a dictionary.

set_ops(ops: List[ImageOperation] | Dict[str, ImageOperation])#

Sets the operations to be performed. The operations can be passed as either a list of ImageOperation instances or a dictionary mapping operation names to ImageOperation instances. This method ensures that each operation in the list has a unique name. Raises a TypeError if the input is neither a list nor a dictionary.

Parameters:

ops (List[ImageOperation] | Dict[str, ImageOperation]) – A list of ImageOperation objects or a dictionary where keys are operation names and values are ImageOperation objects.

Raises:

TypeError – If the input is not a list or a dictionary.

sync_widgets_from_state() None#

Push internal state into widgets.

Return type:

None

to_json(filepath: str | Path | None = None) str#

Serialize the pipeline configuration to JSON format.

This method captures the pipeline’s operations, measurements, and configuration flags. It excludes internal state (attributes starting with ‘_’) and pandas DataFrames to keep the serialization clean and focused on reproducible configuration.

Parameters:

filepath (str | Path | None) – Optional path to save the JSON. If None, returns JSON string. Can be a string or Path object.

Returns:

JSON string representation of the pipeline configuration.

Return type:

str

Example

Serialize a pipeline to JSON format
>>> from phenotypic import ImagePipeline
>>> from phenotypic.detect import OtsuDetector
>>> from phenotypic.measure import MeasureShape
>>>
>>> pipe = ImagePipeline(ops=[OtsuDetector()], meas=[MeasureShape()])
>>> json_str = pipe.to_json()
>>> pipe.to_json('my_pipeline.json')  # Save to file
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.

Parameters:
  • blur_sigma (int)

  • blur_mode (str)

  • blur_cval (float)

  • blur_truncate (float)

  • detector_thresh_method (Literal['otsu', 'mean', 'local', 'triangle', 'minimum', 'isodata'])

  • detector_subtract_background (bool)

  • detector_remove_noise (bool)

  • detector_footprint_radius (int)

  • detector_smoothing_sigma (float)

  • detector_min_peak_distance (int | None)

  • detector_peak_prominence (float | None)

  • detector_edge_refinement (bool)

  • texture_scale (int | List[int])

  • texture_quant_lvl (Literal[8, 16, 32, 64])

  • texture_enhance (bool)

  • texture_warn (bool)

  • benchmark (bool)

  • verbose (bool)