phenotypic.measure.MeasureSize#

class phenotypic.measure.MeasureSize[source]#

Bases: MeasureFeatures

Measure basic size metrics of detected microbial colonies.

This class extracts two fundamental size metrics: Area (colony pixel count) and Integrated Intensity (total grayscale brightness). These measurements are extracted from shape and intensity analyses but are provided as a lightweight convenience class for quick size assessment without full morphological or intensity statistical analysis.

Intuition: Colony size and brightness are primary phenotypic traits in high-throughput screening. Area directly reflects biomass and growth extent on the agar surface. Integrated Intensity approximates optical density without requiring cell suspension, making it useful for time-course growth tracking. Together, these metrics enable rapid size-based sorting and quality filtering.

Use cases (agar plates): - Quickly assess colony size distribution on a plate for quality control. - Track colony growth kinetics over time via area measurements at multiple time points. - Estimate total biomass via integrated intensity (sum of all pixel values). - Filter colonies by minimum size threshold to exclude aborted or contaminating growth. - Rank colonies by size for automated picking or downstream processing.

Caveats: - Area is measured in pixels; it must be scaled by pixel-to-micron conversion factors if physical

dimensions are needed.

  • Integrated intensity is sensitive to imaging conditions (lighting, exposure, camera gain); absolute values are not comparable across different imaging setups without normalization.

  • Both metrics depend on accurate segmentation; over- or under-segmentation distorts size estimates.

  • For size-normalized intensity analysis (e.g., intensity per unit area), use MeasureIntensity.mean instead of integrated intensity, or divide integrated intensity by area.

  • Area does not distinguish between a single solid colony and multiple touching fragments; use MeasureGridSpread or object count metrics for multi-object detection in grid sections.

Returns:
pd.DataFrame: Object-level size measurements with columns:
  • Label: Unique object identifier.

  • Area: Number of pixels occupied by the colony.

  • IntegratedIntensity: Sum of grayscale pixel values in the colony (proxy for biomass/OD).

Examples:
Quick size assessment and filtering
from phenotypic import Image
from phenotypic.detect import OtsuDetector
from phenotypic.measure import MeasureSize

# Load and detect colonies
image = Image.from_image_path("colony_plate.jpg")
detector = OtsuDetector()
image = detector.operate(image)

# Measure size
sizer = MeasureSize()
sizes = sizer.operate(image)

# Filter colonies by size (exclude very small or very large)
min_area, max_area = 50, 5000  # pixels
good_colonies = sizes[
    (sizes['Size_Area'] >= min_area) &
    (sizes['Size_Area'] <= max_area)
]
print(f"Colonies within size range: {len(good_colonies)}/{len(sizes)}")
Track colony growth over time
# Load images from multiple time points
import pandas as pd
from phenotypic import Image
from phenotypic.detect import OtsuDetector
from phenotypic.measure import MeasureSize

detector = OtsuDetector()
sizer = MeasureSize()

# Simulate time-series measurements
growth_data = []
for timepoint_h in [0, 6, 12, 24, 48]:
    img_path = f"plate_t{timepoint_h}h.jpg"
    image = Image.from_image_path(img_path)
    image = detector.operate(image)
    sizes = sizer.operate(image)
    sizes['TimePoint_h'] = timepoint_h
    growth_data.append(sizes)

# Combine and analyze
growth_df = pd.concat(growth_data, ignore_index=True)
# Track individual colonies and compute growth rate (simplified)
avg_area = growth_df.groupby('TimePoint_h')['Size_Area'].mean()
print("Average colony area over time:")
print(avg_area)
Category: SIZE#

Name

Description

Area

Total number of pixels occupied by the microbial colony.Larger areas typically indicate more robust growth or longer incubation times.

IntegratedIntensity

The sum of the object's grayscale pixels. Calculated as$sum{pixel values}*area$

Methods

__init__

measure

Execute the measurement operation on a detected-object image.

__del__()#

Automatically stop tracemalloc when the object is deleted.

measure(image, include_meta=False)#

Execute the measurement operation on a detected-object image.

This is the main public API method for extracting measurements. It handles: input validation, parameter extraction via introspection, calling the subclass-specific _operate() method, optional metadata merging, and exception handling.

How it works (for users):

  1. Pass your processed Image (with detected objects) to measure()

  2. The method calls your subclass’s _operate() implementation

  3. Results are validated and returned as a pandas DataFrame

  4. If include_meta=True, image metadata (filename, grid info) is merged in

How it works (for developers):

When you subclass MeasureFeatures, you only implement _operate(). This measure() method automatically:

  • Extracts __init__ parameters from your instance (introspection)

  • Passes matched parameters to _operate() as keyword arguments

  • Validates the Image has detected objects (objmap)

  • Wraps exceptions in OperationFailedError with context

  • Merges grid/object metadata if requested

Parameters:
  • image (Image) – A PhenoTypic Image object with detected objects (must have non-empty objmap from a prior detection operation).

  • include_meta (bool, optional) – If True, merge image metadata columns (filename, grid position, etc.) into the results DataFrame. Defaults to False.

Returns:

Measurement results with structure:

  • First column: OBJECT.LABEL (integer IDs from image.objmap[:])

  • Remaining columns: Measurement values (float, int, or string)

  • One row per detected object

If include_meta=True, additional metadata columns are prepended before OBJECT.LABEL (e.g., Filename, GridRow, GridCol).

Return type:

pd.DataFrame

Raises:

OperationFailedError – If _operate() raises any exception, it is caught and re-raised as OperationFailedError with details including the original exception type, message, image name, and operation class. This provides consistent error handling across all measurers.

Notes

  • This method is the main entry point; do not override in subclasses

  • Subclasses implement _operate() only, not this method

  • Automatic memory profiling is available via logging configuration

  • Image must have detected objects (image.objmap should be non-empty)

Examples

Basic measurement extraction
from phenotypic import Image
from phenotypic.measure import MeasureSize
from phenotypic.detect import OtsuDetector

# Load and detect
image = Image.from_image_path('plate.jpg')
image = OtsuDetector().operate(image)

# Extract measurements
measurer = MeasureSize()
df = measurer.measure(image)
print(df.head())
Include metadata in measurements
# With image metadata (filename, grid info)
df_with_meta = measurer.measure(image, include_meta=True)
print(df_with_meta.columns)
# Output: ['Filename', 'GridRow', 'GridCol', 'OBJECT.LABEL',
#          'Area', 'IntegratedIntensity', ...]