Python API#

cp_anywhere.api#

NumPy input validation and the public CP-Anywhere measurement result.

class src.cp_anywhere.api.MeasurementResult(image_id: str, features: dict[str, dict[str, float | int | ndarray]], object_ids: dict[str, ndarray], relationships: list[dict[str, str | int]])[source]#

Bases: object

Typed feature columns and directed neighbor edges for one image.

features: dict[str, dict[str, float | int | ndarray]]#
image_id: str#
object_ids: dict[str, ndarray]#
relationships: list[dict[str, str | int]]#
rows() → list[dict[str, str | int | float]][source]#

Return a long table with one row per feature and object ID.

select_scopes(scopes: Iterable[str]) → MeasurementResult[source]#

Return a copy keeping only the named feature scopes (plus their object_ids) – e.g. to restrict to_sqlite()/ to_duckdb()/to_parquet() to a chosen subset of this result’s object tables (mirrors real CellProfiler’s own ExportToDatabase “export measurements for all/no/selected objects” setting; see spec/database-export.md). relationships passes through unchanged – it carries no scope of its own, and none of the wide-table export methods read it.

to_arrow(path: str | Path) → None[source]#

Write every feature row as an Arrow IPC (Feather v2) file.

One row per object per feature column, the same long-form shape as rows()/to_csv(), covering all feature data (every scope, object, and column) in a single typed Arrow table – image_id/scope/feature as strings, object_id as int64, value as float64 (NaN/Infinity preserved natively, unlike to_json()’s string markers).

to_csv(path: str | Path) → None[source]#

Write long-form feature rows with nonfinite values kept as strings.

to_duckdb(path: str | Path, *, if_exists: str = 'append') → None[source]#

Write/append wide Per_Image/Per_<ObjectName> tables (CellProfiler’s own ExportToDatabase naming convention, one row per image or object, one column per feature) into a DuckDB database file.

if_exists="append" (the default) adds this result’s rows to any existing tables at path – the usual way to accumulate one combined dataset across many images, since measure() itself always processes one image at a time. "replace" drops and recreates every table first.

to_json(path: str | Path) → None[source]#

Write the reference-compatible feature and relationship structure.

to_parquet(path: str | Path, *, mode: str = 'long', join: str = 'outer', if_exists: str = 'append', max_rows_per_file: int = 100_000) → None[source]#

Write this result’s feature data as real Apache Parquet file(s).

mode="long" (the default): path is a single file, written in the same long-form shape as to_arrow() (one row per object per feature column).

mode="wide": the traditional, tabular shape – path is a directory (created if missing); one file per feature scope is written into it, Per_Image.parquet plus one Per_<ObjectName>.parquet per object set (CellProfiler’s own ExportToDatabase table-naming convention, matching to_duckdb()/to_sqlite()’s own tables exactly). Each file has image_id (and, for object scopes, object_id) columns plus one real, named column per feature – feature names are the column names, no extra lookup needed.

mode="array": same per-scope files and id columns as "wide", but every feature is packed into a single features column instead of one column each, as one fixed-size list per row (Arrow FixedSizeListArray – the most direct way Parquet/Arrow represents a per-row numeric vector of known length; it round-trips straight into a dense (n_rows, n_features) numpy array with no separate decoding step). Reading a bare feature array back tells you nothing about which feature each position is; the file’s own Parquet schema metadata carries the exact ordered feature name list for that column, read back with read_parquet_feature_names() – no sidecar file to lose or fall out of sync.

mode="joined": a single combined, CytoTable-style wide table – one row per object, every object scope joined together on object_id (join="outer", the default: every object_id seen in any scope, with nulls where a scope has no matching object; join="inner": only object_ids present in every scope), each scope’s feature columns prefixed with that scope’s name (Cells_Intensity_MeanIntensity_DNA, Nuclei_AreaShape_Area, …) to avoid name collisions between scopes, with every Image-scope feature broadcast onto every row with an Image_ prefix. This assumes matching object_id values across scopes identify the same physical object – true whenever one object set was derived from another (as most of this project’s own fixtures are; see spec/compatibility.md), not guaranteed for independently segmented object sets with no declared parent-child relationship (cp_anywhere has no RelateObjects equivalent). Neighbors relationship rows have no natural per-object column and are not included.

path may be a single .parquet file (one write, no pagination beyond Parquet’s own row groups) or a directory, in which case this writes a real Parquet dataset via pyarrow.dataset.write_dataset – max_rows_per_file bounds each fragment file’s row count (Parquet’s own built-in pagination mechanism, not a bespoke chunking scheme; the 100,000-row default is a common balance between per-file overhead and query/memory efficiency). Calling this repeatedly with a directory path – the usual way to build one combined multi-image dataset, since measure() always processes one image at a time – defaults to if_exists="append", adding a new, uniquely-named fragment file each call without touching existing ones; if_exists="replace" deletes the directory first.

to_sqlite(path: str | Path, *, if_exists: str = 'append') → None[source]#

Write/append the same wide Per_Image/Per_<ObjectName> tables as to_duckdb(), but as SQLite STRICT tables – every column has a declared, enforced type (TEXT/INTEGER/REAL) instead of SQLite’s legacy, permissive type affinity. Requires SQLite 3.37+ (STRICT syntax support); raises RuntimeError naming the running SQLite’s version otherwise, rather than failing on the first CREATE TABLE with a confusing syntax error.

if_exists has the same “append” (default, accumulate across images) / “replace” (drop and recreate) meaning as to_duckdb().

src.cp_anywhere.api.measure(images: Mapping[str, object], objects: Mapping[str, object], *, mask: object | None = None, image_id: str = 'Image', families: Sequence[str] | None = None, neighbors_scopes: Sequence[str] | None = None, neighbors_expand: Sequence[str] | None = None, neighbors_distances: Mapping[str, int] | None = None, neighbors_full_objects: Mapping[str, object] | None = None, size_shape_calculate_zernikes: bool = True, size_shape_calculate_advanced: bool = False) → MeasurementResult[source]#

Measure 2D or 3D arrays with the selected CellProfiler 4.2.8 settings.

Float64 C-contiguous images are borrowed by Rust. Other numeric images and strided arrays are converted once. Do not mutate inputs during this call.

The original three default families are unchanged. Select families=["object_size_shape"] explicitly for 2D shape measurements. size_shape_calculate_zernikes=True adds 30 Zernike columns to the 25 standard columns; size_shape_calculate_advanced=True adds 53 moment/inertia columns. Shape measurements ignore the image mask and require consecutive object IDs starting at 1. Sparse shape labels and 3D shape requests raise errors, not misaligned or substitute columns.

neighbors_scopes selects which object set(s) MeasureObjectNeighbors runs against itself. Defaults to ("Cells",) when the "neighbors" family is selected and neighbors_scopes is omitted, matching this project’s original declared scope exactly, byte-for-byte (every pre-existing fixture, golden comparison, and caller is unaffected). Pass e.g. neighbors_scopes=("Nuclei", "Cells") to compute it for multiple object sets in one call instead – each one independently, with its own feature columns and relationship rows tagged by an "object_name" key, matching how real CellProfiler pipelines invoke MeasureObjectNeighbors once per object set.

neighbors_expand names which of those scopes use CellProfiler’s “Expand until adjacent” distance method instead of the default “Adjacent”: every background pixel of that scope’s own geometry (neighbors_full_objects when supplied, else its own labels) is first assigned to its nearest foreground pixel’s label (a 2D-only Voronoi expansion – raises if the image is 3D), and touching/ relationship-edge detection runs on that fully covered label image; object centers and the closest-object/distance/angle columns still use the original, unexpanded geometry, exactly matching real CellProfiler’s own run(). Each name must be one of the active neighbors scopes. Columns get an _Expanded suffix instead of _Adjacent for every scope named here.

neighbors_distances maps active scopes to positive integer pixel distances for “Within a specified distance” (2D only). Columns end in the distance, for example Neighbors_NumberOfNeighbors_5. A scope cannot be configured in both neighbors_distances and neighbors_expand.

neighbors_full_objects supplies each scope’s diagnostic geometry (CellProfiler’s objects.small_removed_segmented). Both primary and secondary segmentation results expose it as small_removed_labels. The core matches diagnostic IDs to retained IDs by pixel overlap. Diagnostic objects omitted from the kept set can affect counts, touching percentages, distances, and angles, but do not get output rows or relationship edges. Closest-object numbers are recomputed among retained objects, matching CellProfiler. Which excluded objects appear in the diagnostic layer depends on the segmentation module; primary segmentation’s layer already excludes border objects. A scope with no entry here (the default) uses its kept labels.

src.cp_anywhere.api.read_parquet_feature_names(path: str | Path) → list[str][source]#

Read back the ordered feature name list embedded in a MeasurementResult.to_parquet(..., mode="array") file’s Parquet schema metadata – the position of each name in the returned list matches the position of its value in that file’s features fixed-size-list column. Raises ValueError naming the path if it has no such metadata (e.g. a plain mode="long" file).

cp_anywhere.io#

The simplest entry point for files on disk: cp_anywhere.io.measure_files() accepts TIFF/OME-TIFF, PNG, or saved NumPy array paths (or already-loaded arrays) directly and returns a tidy pandas.DataFrame, instead of requiring images to be pre-converted to NumPy arrays first.

Load images and label arrays directly from common file formats.

This is the simple entry point for users with ordinary microscopy files (TIFF/OME-TIFF, PNG, or saved NumPy arrays) who do not want to pre-convert anything by hand. measure_files wraps cp_anywhere.api.measure() and returns a tidy pandas.DataFrame instead of a MeasurementResult.

src.cp_anywhere.io.load_array(source: object) → ndarray[source]#

Load one image or label array from a file path, or pass an array through.

Dispatches on file suffix: .npy via numpy.load(), .tif/ .tiff via tifffile, and .png/.jpg/.jpeg/.bmp/ .gif via Pillow. An already-loaded numpy.ndarray is returned unchanged.

src.cp_anywhere.io.measure_files(images: Mapping[str, object] | str | Path, objects: Mapping[str, object] | str | Path, *, mask: object | None = None, image_id: str = 'Image', families: Sequence[str] | None = None) → pd.DataFrame[source]#

Measure images and objects given as file paths (or arrays), as a table.

images/objects may each be a single path/array (named “DNA” and “Cells” respectively) or a mapping of channel/object-set name to path/array, exactly like cp_anywhere.api.measure() but accepting file paths for any supported format (see load_array()) in addition to already-loaded arrays. Returns one row per object per feature column (see cp_anywhere.api.MeasurementResult.rows()).

cp_anywhere.segment#

Object segmentation includes cp_anywhere.identify_primary_objects(), cp_anywhere.identify_secondary_objects(), and cp_anywhere.identify_tertiary_objects(). The native implementations use the corresponding CellProfiler modules as the compatibility oracle – see segmentation coverage for the declared scope and verification status.

Object segmentation, implemented against CellProfiler 4.2.8’s IdentifyPrimaryObjects module (and the shared Threshold module it uses) as the compatibility oracle.

Declared scope: every global and adaptive threshold operation (Manual, Otsu two/three-class, Li, Robust Background, Sauvola), log transform, threshold smoothing, declumping/watershed (Intensity/Shape/Propagate), hole filling (including nested-object absorption), border exclusion, and size/count filtering – see spec/segmentation-modules.md for the exact settings mapping and the explicit remaining gaps (not silent approximations).

CellProfiler’s own Threshold module hard-bounds manual_threshold and threshold_range to [0, 1] and assumes images have been rescaled to that range (its default Image(..., convert=True) divides integer-dtype pixels by their dtype’s max value; float-dtype pixels are never rescaled). identify_primary_objects reproduces that default behavior automatically (rescale=True) so passing a raw uint8/ uint16 image works exactly like a default CellProfiler pipeline, with no manual conversion needed.

The result chains directly into cp_anywhere.measure():

seg = cp_anywhere.identify_primary_objects(dna_image, threshold="otsu")
result = cp_anywhere.measure({"DNA": dna_image}, {"Cells": seg.labels})
class src.cp_anywhere.segment.SecondaryObjectsResult(small_removed_labels: ndarray, labels: ndarray, threshold: float | None)[source]#

Bases: object

Final and pre-filter secondary-object labels.

labels: ndarray#

2D integer label array, same shape as the input image; 0 is background.

small_removed_labels: ndarray#

Pre-filter labels in the original seed numbering, used by neighbors.

threshold: float | None#

The secondary image’s own applied threshold; None for method="distance_n", which never thresholds an image.

property unedited_labels: ndarray#

CellProfiler stores the same grown layer as unedited and small-removed.

class src.cp_anywhere.segment.SegmentationResult(labels: ndarray, small_removed_labels: ndarray, unedited_labels: ndarray, object_count: int, threshold: float, threshold_map: ndarray | None = None, guide_threshold: float | None = None)[source]#

Bases: object

Labels and diagnostics from one identify_primary_objects() call.

guide_threshold: float | None = None#

Corrected global guide used to constrain Adaptive thresholds.

labels: ndarray#

2D integer label array, same shape as the input image; 0 is background.

object_count: int#
small_removed_labels: ndarray#

Labels after the small-object filter only (large objects still present), matching CellProfiler’s objects.small_removed_segmented.

threshold: float#

The threshold value actually applied, after correction/clamping, in the same units as the (possibly rescaled) pixels this was run on.

threshold_map: ndarray | None = None#

Corrected 2D Adaptive threshold array; None for Global thresholding.

unedited_labels: ndarray#

Labels before border, size, count, or final hole filtering.

class src.cp_anywhere.segment.TertiaryObjectsResult(labels: ndarray)[source]#

Bases: object

Tertiary labels, preserving the larger object’s label numbering.

labels: ndarray#
src.cp_anywhere.segment.identify_primary_objects(image: object, *, mask: object | None = None, threshold: str | float | int = 'otsu', rescale: bool = True, threshold_correction_factor: float = 1.0, threshold_range: tuple[float, float] | None = None, exclude_size: bool = False, min_diameter: float = _MIN_DIAMETER_DEFAULT, max_diameter: float = _MAX_DIAMETER_DEFAULT, exclude_border_objects: bool = False, maximum_object_count: int | None = None, fill_holes: str = 'never', threshold_smoothing_scale: float = 0.0, assign_middle_to_foreground: bool = True, robust_background_lower_outlier_fraction: float = 0.05, robust_background_upper_outlier_fraction: float = 0.05, robust_background_averaging_method: str = 'mean', robust_background_variance_method: str = 'sd', robust_background_number_of_deviations: float = 2.0, log_transform: bool = False, threshold_scope: str = 'global', adaptive_window_size: int = 50, unclump_method: str = 'none', watershed_method: str = 'none', smoothing_filter_size: float | None = None, maxima_suppression_size: float | None = None, low_resolution_maxima: bool = False) → SegmentationResult[source]#

Segment one 2D grayscale image into labeled primary objects.

rescale (default True) matches CellProfiler’s own default image loading: integer-dtype images (uint8/uint16/uint32) are divided by their dtype’s max value before thresholding, exactly like CellProfiler’s Image(..., convert=True); float-dtype images are never rescaled (also matching CellProfiler). Set rescale=False to operate on raw pixel values directly instead (matching this project’s measurement API’s own convert=False convention).

threshold is "otsu" (two-class, global, 256-bin histogram – CellProfiler’s default algorithm for any already-float pixel data, which is what every image becomes after rescaling), "otsu_integer" (exact one-bin-per-value histogram; only valid with rescale=False on an integer-dtype image – matches CellProfiler’s Otsu only if CellProfiler would also have skipped rescaling), "otsu_three_class" (a 128-bin, 3-class histogram split; assign_middle_to_foreground picks the lower split, i.e. the middle class counts as foreground, when True (default), or the upper split when False, matching CellProfiler’s "Foreground"/"Background" setting), "li" (Li’s iterative Minimum Cross-Entropy threshold, matching skimage.filters.threshold_li with CellProfiler’s own tolerance formula), "robust_background" (a trimmed mean/median/mode – robust_background_averaging_method – plus a multiple – robust_background_number_of_deviations – of the standard deviation or MAD – robust_background_variance_method – computed after discarding robust_background_lower_outlier_fraction/ robust_background_upper_outlier_fraction of the lowest/highest pixels; matches Threshold.get_threshold_robust_background exactly, including its quirk where a zero lower-fraction also disables the upper trim), "sauvola" (a local mean/standard- deviation formula over a sliding window, only valid with threshold_scope="adaptive" – matches skimage.filters.threshold_sauvola; CellProfiler’s own global_operation Choice does not even include Sauvola, so this raises if combined with threshold_scope="global"), or a numeric manual threshold value, interpreted in the same units as the (possibly rescaled) pixels actually compared against it.

threshold_scope (default "global") matches Threshold.threshold_scope: "global" applies one scalar threshold to the whole image; "adaptive" instead computes a per-pixel threshold map by splitting the image into adaptive_window_size-sized blocks (computing a block threshold with the same algorithm named by threshold – or a direct sliding-window Sauvola computation, which has no block/spline step), blending the block grid across the image with a tensor-product B-spline (matching scipy.interpolate.RectBivariateSpline), and finally clamping the result to [0.7, 1.5] * guide_threshold (the ordinary global threshold, used only as a bound; for "sauvola" this guide is computed via "li", matching CellProfiler’s own shared branch). threshold_map (a same-shape array) and guide_threshold on the returned SegmentationResult are None unless threshold_scope="adaptive"; "manual" and "otsu_integer" are not supported with adaptive scope (CellProfiler’s own local_operation Choice does not include either).

log_transform (default False) matches CellProfiler’s Threshold.log_transform setting, meaningful only when threshold is "otsu", "otsu_three_class", or "li" (CellProfiler itself only exposes this setting for those global operations; it is silently ignored for "otsu_integer", "robust_background", and numeric manual thresholds, matching CellProfiler’s own behavior). When enabled, the threshold is computed on a log-transformed, [0, 1]-rescaled copy of the entire image (not just the masked subset) and mapped back before threshold_correction_factor/clamping, exactly matching centrosome.threshold.log_transform/inverse_log_transform.

exclude_size/min_diameter/max_diameter match CellProfiler’s IdentifyPrimaryObjects size filter: objects whose pixel area falls outside pi * diameter^2 / 4 for the given diameter bounds are removed.

exclude_border_objects (IdentifyPrimaryObjects.exclude_border_objects) removes any object touching the image border (or, if mask is given and nothing touches the image border directly, any object touching the mask’s own border instead).

maximum_object_count (IdentifyPrimaryObjects.maximum_object_count, only enforced when not None) erases every object if the final count exceeds this value, matching CellProfiler’s LIMIT_ERASE.

fill_holes (IdentifyPrimaryObjects.fill_holes) is one of "never" (default), "after_declump_only" (fills background holes enclosed by a single object, after border/size filtering), or "after_thresholding_and_declump" (also fills holes in the binary foreground mask before labeling, limited to area < max_diameter^2). A background region bordered by two or more different objects (not fully enclosed by one) is left unfilled, matching centrosome.cpmorphology.fill_labeled_holes exactly, including its handling of a small object fully nested inside a larger one (absorbed into the enclosing label) and multi-level nested holes.

threshold_smoothing_scale (Threshold.threshold_smoothing_scale, default 0.0 – no smoothing) blurs the image used for the foreground/background comparison (not the value used to compute the threshold, which is always the unsmoothed image) with a Gaussian of sigma = threshold_smoothing_scale / 0.6744 / 2.0, matching CellProfiler’s apply_threshold exactly, including its mask-bleed-over correction near the image border.

unclump_method/watershed_method (IdentifyPrimaryObjects.unclump_method/watershed_method) separate touching objects after initial labeling and before border/size filtering – matching separate_neighboring_objects’s exact position in CellProfiler’s pipeline. unclump_method is "none" (default; no separation), "intensity" (find local intensity maxima in a Gaussian-smoothed copy of the image), or "shape" (find local maxima of the Euclidean distance transform of the foreground, jittered with CellProfiler’s own fixed-seed(0) legacy-RNG noise to break exact ties). watershed_method is "none" (default), "intensity" (watershed on 1 - image), "shape" (watershed on the negated distance transform – reuses the same jittered transform computed above when unclump_method="shape" too, matching CellProfiler’s own if distance_transformed_image is None check), or "propagate" (centrosome.propagate.propagate, a distinct non-watershed algorithm; ignores both image and distance-transform inputs, geometric distance only). Both must be set to something other than "none" for separation to actually run, matching CellProfiler’s own UN_NONE/WA_NONE no-op check.

smoothing_filter_size/maxima_suppression_size override CellProfiler’s own automatic formulas (2.35 * min_diameter / 3.5 and min_diameter / 1.5 respectively) when given explicitly, matching automatic_smoothing/automatic_suppression set to False with an explicit Float Setting value. low_resolution_maxima (IdentifyPrimaryObjects.low_res_maxima) only takes effect when min_diameter > 10.0 (CellProfiler’s own gate); when both are true, maxima are found on a downsampled copy of the image for speed – not yet implemented, raises if triggered.

src.cp_anywhere.segment.identify_secondary_objects(image: object, primary_labels: object, *, primary_labels_in: object | None = None, method: str = 'propagation', mask: object | None = None, threshold: str | float | int = 'otsu', rescale: bool = True, threshold_correction_factor: float = 1.0, threshold_range: tuple[float, float] | None = None, threshold_smoothing_scale: float = 0.0, log_transform: bool = False, threshold_scope: str = 'global', adaptive_window_size: int = 50, assign_middle_to_foreground: bool = True, robust_background_lower_outlier_fraction: float = 0.05, robust_background_upper_outlier_fraction: float = 0.05, robust_background_averaging_method: str = 'mean', robust_background_variance_method: str = 'sd', robust_background_number_of_deviations: float = 2.0, regularization_factor: float = 0.05, distance_to_dilate: float = 10.0, fill_holes: bool = False) → SecondaryObjectsResult[source]#

Grow a secondary object (e.g. "Cells") around each primary object (e.g. "Nuclei"), matching CellProfiler 4.2.8’s IdentifySecondaryObjects module.

image is the secondary stain image (e.g. a cell-membrane or whole-cell marker); primary_labels is the final, kept primary object set (e.g. SegmentationResult.labels from identify_primary_objects()) – a grown secondary object is kept only if its seed primary object survived there.

primary_labels_in accepts the unedited primary labels, before size or border filtering. Pass SegmentationResult.unedited_labels from the upstream primary result. The Rust core retains edge-touching seeds and removes other seed pixels wherever primary_labels is zero, matching CellProfiler. Grown regions are mapped to retained primary IDs by overlap, so renumbered primaries stay aligned. If omitted, the kept primary array supplies the seeds; excluded edge objects cannot participate because their pixels are unavailable.

method is "propagation" (the module’s own default: weighted shortest-path region growing, bounded by a threshold of image, steered by regularization_factor – 0 favors image intensity, larger values favor Euclidean geometry) or "distance_n" (a fixed-radius Euclidean expansion bounded by distance_to_dilate, with no image or threshold involved at all), or "watershed_image" (watershed on inverted intensity within the threshold foreground and seed mask). "distance_b" and "watershed_gradient" are not supported.

threshold/rescale/threshold_correction_factor/ threshold_range/threshold_smoothing_scale/log_transform/ threshold_scope/adaptive_window_size/ assign_middle_to_foreground/robust_background_* all match identify_primary_objects()’s own identically-named parameters exactly (the secondary image’s threshold uses the same machinery, with no size/border/declump filtering applied to it – matching IdentifySecondaryObjects’s own plain threshold-and- binarize step). Ignored entirely for method="distance_n".

fill_holes uses CellProfiler’s labeled-hole graph, but changes only background pixels. Existing nested foreground labels survive. small_removed_labels retains the grown labels before filtering, in the original seed numbering, for downstream neighbor measurements.

src.cp_anywhere.segment.identify_tertiary_objects(primary_labels: object, secondary_labels: object, *, shrink_primary: bool = True) → TertiaryObjectsResult[source]#

Subtract smaller objects from larger objects on the same 2D grid.

With shrink_primary=True (CellProfiler’s default), retain the smaller objects’ one-pixel, eight-connected outline. With False, remove every smaller-object pixel. Output IDs are the larger objects’ IDs, not newly numbered connected components. Inputs are never modified. Crop/resize metadata and parent measurements are not provided by this array API; grids must already match.

Segmentation preview#

Use cp_anywhere.preview_segmentation() to inspect object boundaries over a grayscale image or view labels as filled colors. This is a 2D display helper, not an implementation of the CellProfiler desktop window or a pipeline module.

Display 2D segmentation results without changing the source arrays.

src.cp_anywhere.preview.preview_segmentation(labels: ndarray, image: ndarray | None = None, *, mode: Literal['outlines', 'labels'] = 'outlines') → ndarray[tuple[Any, ...], dtype[uint8]][source]#

Return an 8-bit RGB preview of one 2D label image.

Zero is background. Positive integers are object IDs and may have gaps. In outlines mode, draw green lines on the object side of boundaries. A boundary touches a different label or the image edge along a pixel side. Supply a same-shape grayscale image to see the outlines in context. The finite image range maps to black through white. Nonfinite pixels and constant images display as black. With no image, the background is black.

In labels mode, omit image. Each object gets a color based on its original ID, and the palette repeats. The background stays black.

This function does not change the image or labels. Use the returned array for display or export, not as a substitute for the original labels.

cp_anywhere.cppipe#

Importing real CellProfiler .cppipe pipeline files (cp_anywhere.load_pipeline()) – see CellProfiler pipeline import for the declared scope and every explicit gap.

Import real CellProfiler .cppipe pipeline files, translating the settings of every module cp_anywhere implements (IdentifyPrimaryObjects, MeasureImageIntensity, MeasureObjectIntensity, MeasureObjectNeighbors) into this project’s own configuration – not a full pipeline execution engine.

The .cppipe text format (header lines, then one block per module: ModuleName:[attr:'val'|...] followed by indented, strictly positional Label:Value setting lines – the label text is decorative and discarded, exactly as real CellProfiler’s own loader discards it) was reverse-engineered from the real serializer (cellprofiler_core.pipeline.io._v5.dump, the pinned 4.2.8 source), not guessed: every field order, separator, and value encoding below was confirmed by generating real pipeline files with the pinned CellProfiler oracle and reading their literal text. See spec/cppipe-compatibility.md for the full settings-mapping table and every explicit gap.

This module has no CellProfiler dependency – replicating that would require re-implementing CellProfiler’s own per-module upgrade_settings version-migration chains (years of legacy-format branches per module), which is explicitly out of scope. Instead, this importer accepts only the current variable_revision_number for each supported module (the one the pinned 4.2.8 oracle itself writes) and raises a clear, explicit error naming the unsupported revision otherwise – asking the user to re-open and re-save the pipeline in a current CellProfiler first, rather than silently mis-translating an older settings layout.

Pipeline input/organization modules (Images, Metadata, NamesAndTypes, Groups, and anything else this module does not explicitly translate) are recognized and skipped, not silently dropped: see Pipeline.skipped_modules. This importer does not replicate CellProfiler’s own file-matching/grouping logic; the caller supplies already-loaded image arrays by the same names the pipeline’s IdentifyPrimaryObjects/Measure* modules reference.

class src.cp_anywhere.cppipe.ColocalizationStep(images: tuple[str, ...], objects: tuple[str, ...], threshold_percent: float, fast_costes: str, do_corr_and_slope: bool, do_manders: bool, do_rwc: bool, do_overlap: bool, do_costes: bool, wants_image_measurements: bool, wants_object_measurements: bool)[source]#

Bases: object

One translated MeasureColocalization module: every requested image (every i < j pair is measured, matching real CellProfiler’s own get_image_pairs()), at most one object set, and cp_anywhere.measure_colocalization’s own keyword settings. 2D only – real CellProfiler’s 3D volumetric case is an explicit, documented gap. “Run all metrics?” is UI-only and not represented here; the five do_* flags are read directly, matching real CellProfiler’s own run().

do_corr_and_slope: bool#
do_costes: bool#
do_manders: bool#
do_overlap: bool#
do_rwc: bool#
fast_costes: str#
images: tuple[str, ...]#
objects: tuple[str, ...]#
threshold_percent: float#
wants_image_measurements: bool#
wants_object_measurements: bool#
exception src.cp_anywhere.cppipe.CppipeError[source]#

Bases: ValueError

An explicit, named incompatibility (not a parse failure) – e.g. an unsupported module revision, an out-of-scope setting value, or a settings combination outside spec/cppipe-compatibility.md’s declared scope. Always names the offending module/setting/value; never a silent fallback.

class src.cp_anywhere.cppipe.ExportToDatabaseStep(sqlite_file: str, objects_choice: str, objects: tuple[str, ...], if_exists: str)[source]#

Bases: object

One translated ExportToDatabase module. Only SQLite output is supported (no MySQL server connection of any kind), and only “one table per object type” (separate_object_tables’s own OT_PER_OBJECT – real CellProfiler’s default, “Single object table”, combines every selected object’s measurements into one row per object and is an explicit, documented gap here; use MeasurementResult.to_parquet(mode="joined") instead if you want that shape). Table prefixes (want_table_prefix), the CellProfiler Analyst properties file, the object-relationship table, and the per-image aggregate (mean/median/std-dev) columns are also explicit, documented gaps – none of to_sqlite/to_duckdb generate them.

sqlite_file is the bare filename from the module’s own setting: like every other translated step, this project never resolves a CellProfiler Directory setting’s “Default Output/Input Folder” choice to an absolute path – the caller supplies path to write(), exactly as the caller supplies every image array to Pipeline.run().

if_exists: str#
objects: tuple[str, ...]#
objects_choice: str#
selected_scopes(result: MeasurementResult) → tuple[str, ...][source]#

The result.features scopes this step would write.

sqlite_file: str#
write(result: MeasurementResult, path: str | Path) → None[source]#

Write result’s selected scopes to a SQLite file at path via MeasurementResult.to_sqlite(), honoring this step’s objects_choice/objects selection and if_exists overwrite policy.

class src.cp_anywhere.cppipe.GranularityStep(images: tuple[str, ...], objects: tuple[str, ...], subsample_size: float, image_sample_size: float, element_size: int, granular_spectrum_length: int)[source]#

Bases: object

One translated MeasureGranularity module: every requested image name (each measured independently, matching real CellProfiler), the object sets to also measure per-object spectra on, and cp_anywhere.measure_granularity’s own keyword settings.

element_size: int#
granular_spectrum_length: int#
image_sample_size: float#
images: tuple[str, ...]#
objects: tuple[str, ...]#
subsample_size: float#
class src.cp_anywhere.cppipe.IlluminationApplyImage(input_image: str, output_image: str, illumination_function_image: str, divide_or_subtract: str)[source]#

Bases: object

One of CorrectIlluminationApply’s repeated image groups.

divide_or_subtract: str#
illumination_function_image: str#
input_image: str#
output_image: str#
class src.cp_anywhere.cppipe.IlluminationApplyStep(images: tuple[IlluminationApplyImage, ...], truncate_low: bool, truncate_high: bool)[source]#

Bases: object

One translated CorrectIlluminationApply module: every configured image group (CellProfiler lets one module instance apply correction to several images at once, sharing the same truncate settings).

images: tuple[IlluminationApplyImage, ...]#
truncate_high: bool#
truncate_low: bool#
class src.cp_anywhere.cppipe.IlluminationCalculateStep(input_image: str, output_image: str, intensity_choice: str, dilate_objects: bool, object_dilation_radius: int, block_size: int, rescale_option: str, smoothing_method: str, automatic_object_width: str, object_width: float, size_of_smoothing_filter: float)[source]#

Bases: object

One translated CorrectIlluminationCalculate module, "Each" mode only: "All: First cycle"/"All: Across cycles" need the full image set list (every cycle’s own image, not just one), which does not fit Pipeline.run()’s single-image-set signature – an explicit, documented gap (use cp_anywhere.calculate_illumination_across() directly on your own loaded image sequence instead). Convex Hull and Splines smoothing methods are separate, not-yet-implemented gaps (see cp_anywhere.calculate_illumination()); “Retain the averaged/dilated image?” has no equivalent here (this project has no “intermediate image” concept) and is silently not represented – CellProfiler’s own SaveImages module would be needed to save those, not this translator.

automatic_object_width: str#
block_size: int#
dilate_objects: bool#
input_image: str#
intensity_choice: str#
object_dilation_radius: int#
object_width: float#
output_image: str#
rescale_option: str#
size_of_smoothing_filter: float#
smoothing_method: str#
class src.cp_anywhere.cppipe.ImageMathStep(input_image: str, output_image: str, input_factor: float, output_factor: float, addend: float, truncate_low: bool, truncate_high: bool, replace_nan: bool)[source]#

Bases: object

A single-input, unmasked ImageMath None operation.

addend: float#
input_factor: float#
input_image: str#
output_factor: float#
output_image: str#
replace_nan: bool#
truncate_high: bool#
truncate_low: bool#
class src.cp_anywhere.cppipe.IntensityDistributionStep(images: tuple[str, ...], objects: tuple[str, ...], bin_count: int, wants_scaled: bool, maximum_radius: float, zernikes: Literal['none', 'magnitudes', 'magnitudes_and_phase'], zernike_degree: int, additional_bin_groups: tuple[RadialBinGroup, ...] = ())[source]#

Bases: object

One revision 6 radial module with ordered object and bin groups.

The original scalar bin settings describe the first group. Each object group uses its own objects as centers.

additional_bin_groups: tuple[RadialBinGroup, ...] = ()#
bin_count: int#
images: tuple[str, ...]#
maximum_radius: float#
objects: tuple[str, ...]#
wants_scaled: bool#
zernike_degree: int#
zernikes: Literal['none', 'magnitudes', 'magnitudes_and_phase']#
class src.cp_anywhere.cppipe.MeasurementStep(module_name: str, family: str, images: tuple[str, ...], objects: tuple[str, ...], calculate_zernikes: bool = True, calculate_advanced: bool = False, wants_excluded_objects: bool = False, wants_expand: bool = False, neighbors_distance: int | None = None)[source]#

Bases: object

One translated Measure* module’s requested image/object names and which cp_anywhere.measure family it activates.

calculate_advanced: bool = False#
calculate_zernikes: bool = True#
family: str#
images: tuple[str, ...]#
module_name: str#
neighbors_distance: int | None = None#

Pixel distance for a “Within a specified distance” neighbors step.

objects: tuple[str, ...]#
wants_excluded_objects: bool = False#

Whether neighbor geometry uses the object’s small-removed layer.

This matches CellProfiler’s excluded-objects setting. Layer contents depend on the upstream segmentation module, not only this flag.

wants_expand: bool = False#

Whether this neighbors step uses CellProfiler’s “Expand until adjacent” distance method (measure(..., neighbors_expand=...)) instead of the default “Adjacent”. Only meaningful when family == "neighbors".

class src.cp_anywhere.cppipe.Pipeline(segmentation_steps: list[SegmentationStep] = <factory>, secondary_steps: list[SecondaryObjectsStep] = <factory>, tertiary_steps: list[TertiaryObjectsStep] = <factory>, measurement_steps: list[MeasurementStep] = <factory>, granularity_steps: list[GranularityStep] = <factory>, intensity_distribution_steps: list[IntensityDistributionStep] = <factory>, texture_steps: list[TextureStep] = <factory>, colocalization_steps: list[ColocalizationStep] = <factory>, export_steps: list[ExportToDatabaseStep] = <factory>, illumination_calculate_steps: list[IlluminationCalculateStep] = <factory>, illumination_apply_steps: list[IlluminationApplyStep] = <factory>, save_images_steps: list[SaveImagesStep] = <factory>, skipped_modules: list[str] = <factory>, image_math_steps: list[ImageMathStep] = <factory>, image_step_order: list[str] = <factory>)[source]#

Bases: object

A .cppipe file’s translated, cp_anywhere-runnable steps.

Not a full pipeline executor: file-matching/grouping modules (Images, Metadata, NamesAndTypes, Groups, …) are listed in skipped_modules, not run – the caller supplies already-loaded image arrays by name via run().

colocalization_steps: list[ColocalizationStep]#
export_steps: list[ExportToDatabaseStep]#
granularity_steps: list[GranularityStep]#
illumination_apply_steps: list[IlluminationApplyStep]#
illumination_calculate_steps: list[IlluminationCalculateStep]#
image_math_steps: list[ImageMathStep]#
image_step_order: list[str]#
intensity_distribution_steps: list[IntensityDistributionStep]#
measurement_steps: list[MeasurementStep]#
prepare_images(images: Mapping[str, np.ndarray]) → dict[str, np.ndarray][source]#

Return inputs and prepared planes without modifying the caller’s arrays.

run(images: Mapping[str, np.ndarray]) → tuple[dict[str, SegmentationResult], dict[str, SecondaryObjectsResult | TertiaryObjectsResult], MeasurementResult | None][source]#

Prepare images, identify primary/secondary/tertiary objects, and measure.

save_images_steps: list[SaveImagesStep]#
secondary_steps: list[SecondaryObjectsStep]#
segmentation_steps: list[SegmentationStep]#
skipped_modules: list[str]#
tertiary_steps: list[TertiaryObjectsStep]#
texture_steps: list[TextureStep]#
class src.cp_anywhere.cppipe.PipelineModuleCheck(position: int, name: str, status: _ModuleStatus, detail: str)[source]#

Bases: object

Preflight result for one module block, in one-based file order.

detail: str#
name: str#
position: int#
status: _ModuleStatus#
class src.cp_anywhere.cppipe.RadialBinGroup(bin_count: int, wants_scaled: bool, maximum_radius: float)[source]#

Bases: object

One saved radial bin group, in pipeline order.

bin_count: int#
maximum_radius: float#
wants_scaled: bool#
class src.cp_anywhere.cppipe.SaveImagesStep(image_name: str, file_name: str, file_format: str, bit_depth: str, overwrite: bool)[source]#

Bases: object

One translated SaveImages module.

Only save_image_or_figure == "Image" (not "Mask", "Cropping", or "Movie/Stack", which need a cropping mask or multi-cycle frame-stacking concept this project does not have) and file_name_method == "Single name" (not "From image filename"/"Sequential numbers", which need per-image-set source-file/metadata tracking this project does not have) are supported – explicit, documented gaps. "h5" (FF_H5) is a separate, not-yet-implemented gap (see cp_anywhere.save_images.save_array()’s own module docstring); "tiff"/"png"/"jpeg"/"npy" are supported.

Like ExportToDatabaseStep, this project never resolves a CellProfiler Directory setting’s “Default Output/Input Folder” choice to an absolute path – the caller supplies path to write(), exactly as the caller supplies every image array to Pipeline.run(). file_name is kept as the module’s raw name setting. The directory setting is not retained, and write() uses only the caller-supplied destination.

Pipeline.run() does not execute these save steps automatically. Cycle timing, filename measurements, subfolders, and TIFF compression settings are not implemented. See spec/illumination.md.

Real CellProfiler’s own get_bit_depth() forces 8-bit for every file format except TIFF/HDF5, regardless of the bit_depth setting’s own value – effective_bit_depth already applies that rule.

bit_depth: str#
property effective_bit_depth: str#

The bit depth real CellProfiler would actually apply – bit_depth is only honored for TIFF; every other supported format (PNG/JPEG/NPY) is always forced to 8-bit integer (NPY’s own writer then ignores bit depth entirely regardless).

file_format: str#
file_name: str#
image_name: str#
overwrite: bool#
write(image: ndarray, path: str | Path, *, bit_depth: str | None = None) → None[source]#

Write image to path via cp_anywhere.save_images.save_array(), using effective_bit_depth unless bit_depth overrides it. Honors this step’s own overwrite setting.

class src.cp_anywhere.cppipe.SecondaryObjectsStep(input_image: str, primary_object: str, output_object: str, config: dict[str, object])[source]#

Bases: object

One translated IdentifySecondaryObjects module: the input (secondary stain) image name, the primary object name it grows around, the object name it writes, and the identify_secondary_objects kwargs (matching cp_anywhere.segment.identify_secondary_objects()’s own parameter names exactly, so **step.config works directly).

config: dict[str, object]#
input_image: str#
output_object: str#
primary_object: str#
class src.cp_anywhere.cppipe.SegmentationStep(input_image: str, output_object: str, config: dict[str, object])[source]#

Bases: object

One translated IdentifyPrimaryObjects module: an input image name, the object name it writes, and the identify_primary_objects kwargs (matching cp_anywhere.identify_primary_objects()’s own parameter names exactly, so **step.config works directly).

config: dict[str, object]#
input_image: str#
output_object: str#
class src.cp_anywhere.cppipe.TertiaryObjectsStep(primary_object: str, secondary_object: str, output_object: str, shrink_primary: bool)[source]#

Bases: object

Subtract smaller objects from larger objects on the same grid.

output_object: str#
primary_object: str#
secondary_object: str#
shrink_primary: bool#
class src.cp_anywhere.cppipe.TextureStep(images: tuple[str, ...], objects: tuple[str, ...], gray_levels: int, scales: tuple[int, ...], wants_image_measurements: bool, wants_object_measurements: bool)[source]#

Bases: object

One translated MeasureTexture module: every requested image and object name (each image measured against every object set, matching real CellProfiler’s own full cross-product of feature columns), and cp_anywhere.measure_texture’s own keyword settings. 2D only – real CellProfiler’s 3D volumetric correspondence vectors (13 directions instead of 4) are an explicit, documented gap.

gray_levels: int#
images: tuple[str, ...]#
objects: tuple[str, ...]#
scales: tuple[int, ...]#
wants_image_measurements: bool#
wants_object_measurements: bool#
src.cp_anywhere.cppipe.inspect_pipeline(path: str | Path) → tuple[PipelineModuleCheck, ...][source]#

Report each module’s compatibility without reading image files or running it.

src.cp_anywhere.cppipe.load_pipeline(path: str | Path) → Pipeline[source]#

Parse a real CellProfiler .cppipe text file into a Pipeline. Raises CppipeError for any module setting outside spec/cppipe-compatibility.md’s declared scope – never a silent fallback or approximation.

Batch processing#

Apply one translated pipeline to complete, independent image sets. Batch processing does not replace single-field or individual module calls.

Run a translated pipeline on independent image sets.

class src.cp_anywhere.batch.ImageSetResult(image_id: str, primary: dict[str, SegmentationResult], derived: dict[str, SecondaryObjectsResult | TertiaryObjectsResult], measurements: MeasurementResult | None)[source]#

One image set’s labels and measurements, keyed by its caller-supplied ID.

src.cp_anywhere.batch.run_batch(pipeline: Pipeline | str | Path, image_sets: Mapping[str, Mapping[str, str | Path | np.ndarray]], *, workers: int = 1, backend: Literal['thread', 'process'] = 'thread') → Generator[ImageSetResult, None, None][source]#

Run one translated pipeline per image set, in input order.

At most workers image sets are in flight at once. A single image set always runs in the caller. Do not mutate the pipeline, mapping, or arrays while iterating. If you stop early, close the iterator to cancel queued work where possible and wait for running work to finish. Errors propagate with the image ID attached to the traceback.

This function does not match files, group fields, estimate shared maps, or write outputs. Pass any shared calibration images by name with each set. For custom workflows, call Pipeline.run() or individual modules.

Parameters:
  • pipeline – A loaded pipeline or path to a supported .cppipe file.

  • image_sets – Image IDs mapped to named channel paths or arrays. An empty mapping yields no results.

  • workers – Maximum workers. One runs serially, regardless of backend.

  • backend – Use threads (default) or spawned processes. For processes, run from an importable Python script under a main guard. Paths avoid copying input arrays to workers. Results are copied back to the caller.

Yields:

Segmentation and measurement results with the caller’s image ID.

Raises:

ValueError – If the backend, worker count, or image IDs are invalid.