phenotypic.prefab.GridSectionPipeline#
- class phenotypic.prefab.GridSectionPipeline(gaussian_sigma: int = 10, gaussian_mode: str = 'reflect', gaussian_truncate: float = 4.0, clahe_kernel_size: int | None = None, clahe_clip_limit: float = 0.01, median_mode: str = 'nearest', median_cval: float = 0.0, otsu_ignore_zeros: bool = True, otsu_ignore_borders: bool = True, border_remover_size: int | float | None = 50, circularity_cutoff: float = 0.6, small_object_min_size: int = 100, outlier_axis: int | None = None, outlier_stddev_multiplier: float = 1.5, outlier_max_coeff_variance: int = 1, aligner_axis: int = 0, aligner_mode: str = 'edge', section_blur_sigma: int = 5, section_blur_mode: str = 'reflect', section_blur_truncate: float = 4.0, section_median_mode: str = 'nearest', section_median_cval: float = 0.0, section_contrast_lower_percentile: int = 2, section_contrast_upper_percentile: int = 98, section_otsu_ignore_zeros: bool = True, section_otsu_ignore_borders: bool = True, grid_apply_reset_enh_matrix: bool = True, small_object_min_size_2: int = 100, color_white_chroma_max: float = 4.0, color_chroma_min: float = 8.0, color_include_XYZ: bool = False, 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, **kwargs)[source]#
Bases:
PrefabPipelineProvides an image processing pipeline designed for grid-based section-level analysis.
This class defines a sequence of operations and measurements optimized for processing gridded images where each section is analyzed independently. The pipeline includes multiple stages of preprocessing, detection, filtering, and alignment steps, followed by section-level detection and final measurements.
- Parameters:
gaussian_sigma (int)
gaussian_mode (str)
gaussian_truncate (float)
clahe_kernel_size (int | None)
clahe_clip_limit (float)
median_mode (str)
median_cval (float)
otsu_ignore_zeros (bool)
otsu_ignore_borders (bool)
circularity_cutoff (float)
small_object_min_size (int)
outlier_axis (int | None)
outlier_stddev_multiplier (float)
outlier_max_coeff_variance (int)
aligner_axis (int)
aligner_mode (str)
section_blur_sigma (int)
section_blur_mode (str)
section_blur_truncate (float)
section_median_mode (str)
section_median_cval (float)
section_contrast_lower_percentile (int)
section_contrast_upper_percentile (int)
section_otsu_ignore_zeros (bool)
section_otsu_ignore_borders (bool)
grid_apply_reset_enh_matrix (bool)
small_object_min_size_2 (int)
color_white_chroma_max (float)
color_chroma_min (float)
color_include_XYZ (bool)
texture_quant_lvl (Literal[8, 16, 32, 64])
texture_enhance (bool)
texture_warn (bool)
benchmark (bool)
- outlier_axis#
Axis for outlier analysis. None for both, 0 for rows, 1 for columns.
- Type:
Optional[int]
- grid_apply_reset_enh_matrix#
Whether to reset enh_gray before applying section-level pipeline.
- Type:
- texture_quant_lvl#
Quantization level for texture computation.
- Type:
Literal[8, 16, 32, 64]
Methods
Initializes the GridSectionPipeline with customizable operations and measurements.
The class provides an abc_ to process and apply a series of operations on an Image.
Applies processing to the given image and measures the results.
Returns a table of execution times for operations and measurements.
Drop references to the UI widgets.
Deserialize a pipeline from JSON format.
Measures properties of a given image and optionally includes metadata.
Sets the measurements to be used for further computation.
Sets the operations to be performed.
Push internal state into widgets.
Serialize the pipeline configuration to JSON format.
Return (and optionally display) the root widget.
- __init__(gaussian_sigma: int = 10, gaussian_mode: str = 'reflect', gaussian_truncate: float = 4.0, clahe_kernel_size: int | None = None, clahe_clip_limit: float = 0.01, median_mode: str = 'nearest', median_cval: float = 0.0, otsu_ignore_zeros: bool = True, otsu_ignore_borders: bool = True, border_remover_size: int | float | None = 50, circularity_cutoff: float = 0.6, small_object_min_size: int = 100, outlier_axis: int | None = None, outlier_stddev_multiplier: float = 1.5, outlier_max_coeff_variance: int = 1, aligner_axis: int = 0, aligner_mode: str = 'edge', section_blur_sigma: int = 5, section_blur_mode: str = 'reflect', section_blur_truncate: float = 4.0, section_median_mode: str = 'nearest', section_median_cval: float = 0.0, section_contrast_lower_percentile: int = 2, section_contrast_upper_percentile: int = 98, section_otsu_ignore_zeros: bool = True, section_otsu_ignore_borders: bool = True, grid_apply_reset_enh_matrix: bool = True, small_object_min_size_2: int = 100, color_white_chroma_max: float = 4.0, color_chroma_min: float = 8.0, color_include_XYZ: bool = False, 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, **kwargs)[source]#
Initializes the GridSectionPipeline with customizable operations and measurements.
- Parameters:
gaussian_sigma (int) – Standard deviation for Gaussian kernel in initial smoothing.
gaussian_mode (str) – Mode for handling image boundaries during Gaussian smoothing.
gaussian_truncate (float) – Truncate the Gaussian kernel at this many standard deviations.
clahe_kernel_size (int | None) – Size of kernel for CLAHE. If None, automatically calculated.
clahe_clip_limit (float) – Contrast limit for CLAHE.
median_mode (str) – Boundary mode for median filter.
median_cval (float) – Constant value for median filter when mode is ‘constant’.
otsu_ignore_zeros (bool) – Whether to ignore zero pixels in Otsu thresholding.
otsu_ignore_borders (bool) – Whether to ignore border objects in Otsu detection.
border_remover_size (int | float | None) – Size of border region where objects are removed.
circularity_cutoff (float) – Minimum circularity threshold for objects to be retained.
small_object_min_size (int) – Minimum size of objects to retain in first removal step.
outlier_axis (Optional[int]) – Axis for outlier analysis. None for both, 0 for rows, 1 for columns.
outlier_stddev_multiplier (float) – Multiplier for standard deviation in outlier detection.
outlier_max_coeff_variance (int) – Maximum coefficient of variance for outlier analysis.
aligner_axis (int) – Axis for grid alignment (0 for rows, 1 for columns).
aligner_mode (str) – Mode for grid alignment rotation.
section_blur_sigma (int) – Standard deviation for Gaussian kernel in section-level detection.
section_blur_mode (str) – Mode for Gaussian smoothing in section-level detection.
section_blur_truncate (float) – Truncate for Gaussian kernel in section-level detection.
section_median_mode (str) – Boundary mode for median filter in section-level detection.
section_median_cval (float) – Constant value for median filter in section-level detection.
section_contrast_lower_percentile (int) – Lower percentile for contrast stretching in sections.
section_contrast_upper_percentile (int) – Upper percentile for contrast stretching in sections.
section_otsu_ignore_zeros (bool) – Whether to ignore zeros in section-level Otsu detection.
section_otsu_ignore_borders (bool) – Whether to ignore borders in section-level Otsu detection.
grid_apply_reset_enh_matrix (bool) – Whether to reset enh_gray before applying section-level pipeline.
small_object_min_size_2 (int) – Minimum size of objects to retain in second removal step.
color_white_chroma_max (float) – Maximum white chroma value for color measurement.
color_chroma_min (float) – Minimum chroma value for color measurement.
color_include_XYZ (bool) – Whether to include XYZ color space measurements.
texture_scale (int | list[int]) – Scale parameter(s) for Haralick texture features.
texture_quant_lvl (Literal[8, 16, 32, 64]) – Quantization level for texture computation.
texture_enhance (bool) – Whether to enhance image before texture measurement.
texture_warn (bool) – Whether to warn on texture computation errors.
benchmark (bool) – Indicates whether benchmarking is enabled across the pipeline.
- __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:
- 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
- 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:
- 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.
- 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:
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:
- Returns:
The root widget.
- Return type:
ipywidgets.Widget
- Raises:
ImportError – If ipywidgets or IPython are not installed.