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:
objectTyped 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 restrictto_sqlite()/to_duckdb()/to_parquet()to a chosen subset of this result’s object tables (mirrors real CellProfiler’s ownExportToDatabase“export measurements for all/no/selected objects” setting; seespec/database-export.md).relationshipspasses 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/featureas strings,object_idas int64,valueas float64 (NaN/Infinity preserved natively, unliketo_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 ownExportToDatabasenaming 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 atpath– the usual way to accumulate one combined dataset across many images, sincemeasure()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):pathis a single file, written in the same long-form shape asto_arrow()(one row per object per feature column).mode="wide": the traditional, tabular shape –pathis a directory (created if missing); one file per feature scope is written into it,Per_Image.parquetplus onePer_<ObjectName>.parquetper object set (CellProfiler’s ownExportToDatabasetable-naming convention, matchingto_duckdb()/to_sqlite()’s own tables exactly). Each file hasimage_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 singlefeaturescolumn instead of one column each, as one fixed-size list per row (ArrowFixedSizeListArray– 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 withread_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 onobject_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 everyImage-scope feature broadcast onto every row with anImage_prefix. This assumes matchingobject_idvalues 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; seespec/compatibility.md), not guaranteed for independently segmented object sets with no declared parent-child relationship (cp_anywhere has noRelateObjectsequivalent).Neighborsrelationship rows have no natural per-object column and are not included.pathmay be a single.parquetfile (one write, no pagination beyond Parquet’s own row groups) or a directory, in which case this writes a real Parquet dataset viapyarrow.dataset.write_dataset–max_rows_per_filebounds 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 directorypath– the usual way to build one combined multi-image dataset, sincemeasure()always processes one image at a time – defaults toif_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 asto_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+ (STRICTsyntax support); raisesRuntimeErrornaming the running SQLite’s version otherwise, rather than failing on the firstCREATE TABLEwith a confusing syntax error.if_existshas the same “append” (default, accumulate across images) / “replace” (drop and recreate) meaning asto_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=Trueadds 30 Zernike columns to the 25 standard columns;size_shape_calculate_advanced=Trueadds 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_scopesselects which object set(s)MeasureObjectNeighborsruns against itself. Defaults to("Cells",)when the"neighbors"family is selected andneighbors_scopesis 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 invokeMeasureObjectNeighborsonce per object set.neighbors_expandnames 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_objectswhen 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 ownrun(). Each name must be one of the active neighbors scopes. Columns get an_Expandedsuffix instead of_Adjacentfor every scope named here.neighbors_distancesmaps active scopes to positive integer pixel distances for “Within a specified distance” (2D only). Columns end in the distance, for exampleNeighbors_NumberOfNeighbors_5. A scope cannot be configured in bothneighbors_distancesandneighbors_expand.neighbors_full_objectssupplies each scope’s diagnostic geometry (CellProfiler’sobjects.small_removed_segmented). Both primary and secondary segmentation results expose it assmall_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’sfeaturesfixed-size-list column. RaisesValueErrornaming the path if it has no such metadata (e.g. a plainmode="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:
.npyvianumpy.load(),.tif/.tiffviatifffile, and.png/.jpg/.jpeg/.bmp/.gifvia Pillow. An already-loadednumpy.ndarrayis 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/objectsmay each be a single path/array (named “DNA” and “Cells” respectively) or a mapping of channel/object-set name to path/array, exactly likecp_anywhere.api.measure()but accepting file paths for any supported format (seeload_array()) in addition to already-loaded arrays. Returns one row per object per feature column (seecp_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:
objectFinal 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;
Noneformethod="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:
objectLabels 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:
objectTertiary 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(defaultTrue) 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’sImage(..., convert=True); float-dtype images are never rescaled (also matching CellProfiler). Setrescale=Falseto operate on raw pixel values directly instead (matching this project’s measurement API’s ownconvert=Falseconvention).thresholdis"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 withrescale=Falseon 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_foregroundpicks the lower split, i.e. the middle class counts as foreground, whenTrue(default), or the upper split whenFalse, matching CellProfiler’s"Foreground"/"Background"setting),"li"(Li’s iterative Minimum Cross-Entropy threshold, matchingskimage.filters.threshold_liwith 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 discardingrobust_background_lower_outlier_fraction/robust_background_upper_outlier_fractionof the lowest/highest pixels; matchesThreshold.get_threshold_robust_backgroundexactly, 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 withthreshold_scope="adaptive"– matchesskimage.filters.threshold_sauvola; CellProfiler’s ownglobal_operationChoice does not even include Sauvola, so this raises if combined withthreshold_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") matchesThreshold.threshold_scope:"global"applies one scalar threshold to the whole image;"adaptive"instead computes a per-pixel threshold map by splitting the image intoadaptive_window_size-sized blocks (computing a block threshold with the same algorithm named bythreshold– 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 (matchingscipy.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) andguide_thresholdon the returnedSegmentationResultareNoneunlessthreshold_scope="adaptive";"manual"and"otsu_integer"are not supported with adaptive scope (CellProfiler’s ownlocal_operationChoice does not include either).log_transform(defaultFalse) matches CellProfiler’sThreshold.log_transformsetting, meaningful only whenthresholdis"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 beforethreshold_correction_factor/clamping, exactly matchingcentrosome.threshold.log_transform/inverse_log_transform.exclude_size/min_diameter/max_diametermatch CellProfiler’sIdentifyPrimaryObjectssize filter: objects whose pixel area falls outsidepi * diameter^2 / 4for the given diameter bounds are removed.exclude_border_objects(IdentifyPrimaryObjects.exclude_border_objects) removes any object touching the image border (or, ifmaskis 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 notNone) erases every object if the final count exceeds this value, matching CellProfiler’sLIMIT_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, matchingcentrosome.cpmorphology.fill_labeled_holesexactly, 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, default0.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 ofsigma = threshold_smoothing_scale / 0.6744 / 2.0, matching CellProfiler’sapply_thresholdexactly, 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 – matchingseparate_neighboring_objects’s exact position in CellProfiler’s pipeline.unclump_methodis"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_methodis"none"(default),"intensity"(watershed on1 - image),"shape"(watershed on the negated distance transform – reuses the same jittered transform computed above whenunclump_method="shape"too, matching CellProfiler’s ownif distance_transformed_image is Nonecheck), 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 ownUN_NONE/WA_NONEno-op check.smoothing_filter_size/maxima_suppression_sizeoverride CellProfiler’s own automatic formulas (2.35 * min_diameter / 3.5andmin_diameter / 1.5respectively) when given explicitly, matchingautomatic_smoothing/automatic_suppressionset toFalsewith an explicitFloatSetting value.low_resolution_maxima(IdentifyPrimaryObjects.low_res_maxima) only takes effect whenmin_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’sIdentifySecondaryObjectsmodule.imageis the secondary stain image (e.g. a cell-membrane or whole-cell marker);primary_labelsis the final, kept primary object set (e.g.SegmentationResult.labelsfromidentify_primary_objects()) – a grown secondary object is kept only if its seed primary object survived there.primary_labels_inaccepts the unedited primary labels, before size or border filtering. PassSegmentationResult.unedited_labelsfrom the upstream primary result. The Rust core retains edge-touching seeds and removes other seed pixels whereverprimary_labelsis 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.methodis"propagation"(the module’s own default: weighted shortest-path region growing, bounded by a threshold ofimage, steered byregularization_factor– 0 favors image intensity, larger values favor Euclidean geometry) or"distance_n"(a fixed-radius Euclidean expansion bounded bydistance_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 matchidentify_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 – matchingIdentifySecondaryObjects’s own plain threshold-and- binarize step). Ignored entirely formethod="distance_n".fill_holesuses CellProfiler’s labeled-hole graph, but changes only background pixels. Existing nested foreground labels survive.small_removed_labelsretains 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. WithFalse, 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
outlinesmode, 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 grayscaleimageto 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
labelsmode, omitimage. 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:
objectOne translated
MeasureColocalizationmodule: every requested image (everyi < jpair is measured, matching real CellProfiler’s ownget_image_pairs()), at most one object set, andcp_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 fivedo_*flags are read directly, matching real CellProfiler’s ownrun().- 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:
ValueErrorAn 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:
objectOne translated
ExportToDatabasemodule. Only SQLite output is supported (no MySQL server connection of any kind), and only “one table per object type” (separate_object_tables’s ownOT_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; useMeasurementResult.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 ofto_sqlite/to_duckdbgenerate them.sqlite_fileis the bare filename from the module’s own setting: like every other translated step, this project never resolves a CellProfilerDirectorysetting’s “Default Output/Input Folder” choice to an absolute path – the caller suppliespathtowrite(), exactly as the caller supplies every image array toPipeline.run().- if_exists: str#
- objects: tuple[str, ...]#
- objects_choice: str#
- selected_scopes(result: MeasurementResult) tuple[str, ...][source]#
The
result.featuresscopes this step would write.
- sqlite_file: str#
- write(result: MeasurementResult, path: str | Path) None[source]#
Write
result’s selected scopes to a SQLite file atpathviaMeasurementResult.to_sqlite(), honoring this step’sobjects_choice/objectsselection andif_existsoverwrite 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:
objectOne translated
MeasureGranularitymodule: every requested image name (each measured independently, matching real CellProfiler), the object sets to also measure per-object spectra on, andcp_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:
objectOne 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:
objectOne translated
CorrectIlluminationApplymodule: 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:
objectOne translated
CorrectIlluminationCalculatemodule,"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 fitPipeline.run()’s single-image-set signature – an explicit, documented gap (usecp_anywhere.calculate_illumination_across()directly on your own loaded image sequence instead).Convex HullandSplinessmoothing methods are separate, not-yet-implemented gaps (seecp_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:
objectA 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:
objectOne 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:
objectOne translated
Measure*module’s requested image/object names and whichcp_anywhere.measurefamily 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
neighborsstep uses CellProfiler’s “Expand until adjacent” distance method (measure(..., neighbors_expand=...)) instead of the default “Adjacent”. Only meaningful whenfamily == "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:
objectA
.cppipefile’s translated,cp_anywhere-runnable steps.Not a full pipeline executor: file-matching/grouping modules (
Images,Metadata,NamesAndTypes,Groups, …) are listed inskipped_modules, not run – the caller supplies already-loaded image arrays by name viarun().- 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:
objectPreflight 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:
objectOne 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:
objectOne translated
SaveImagesmodule.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) andfile_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 (seecp_anywhere.save_images.save_array()’s own module docstring);"tiff"/"png"/"jpeg"/"npy"are supported.Like
ExportToDatabaseStep, this project never resolves a CellProfilerDirectorysetting’s “Default Output/Input Folder” choice to an absolute path – the caller suppliespathtowrite(), exactly as the caller supplies every image array toPipeline.run().file_nameis kept as the module’s raw name setting. The directory setting is not retained, andwrite()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. Seespec/illumination.md.Real CellProfiler’s own
get_bit_depth()forces 8-bit for every file format except TIFF/HDF5, regardless of thebit_depthsetting’s own value –effective_bit_depthalready applies that rule.- bit_depth: str#
- property effective_bit_depth: str#
The bit depth real CellProfiler would actually apply –
bit_depthis 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
imagetopathviacp_anywhere.save_images.save_array(), usingeffective_bit_depthunlessbit_depthoverrides it. Honors this step’s ownoverwritesetting.
- class src.cp_anywhere.cppipe.SecondaryObjectsStep(input_image: str, primary_object: str, output_object: str, config: dict[str, object])[source]#
Bases:
objectOne translated
IdentifySecondaryObjectsmodule: the input (secondary stain) image name, the primary object name it grows around, the object name it writes, and theidentify_secondary_objectskwargs (matchingcp_anywhere.segment.identify_secondary_objects()’s own parameter names exactly, so**step.configworks 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:
objectOne translated
IdentifyPrimaryObjectsmodule: an input image name, the object name it writes, and theidentify_primary_objectskwargs (matchingcp_anywhere.identify_primary_objects()’s own parameter names exactly, so**step.configworks 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:
objectSubtract 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:
objectOne translated
MeasureTexturemodule: every requested image and object name (each image measured against every object set, matching real CellProfiler’s own full cross-product of feature columns), andcp_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
.cppipetext file into aPipeline. RaisesCppipeErrorfor any module setting outsidespec/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
workersimage 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
.cppipefile.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.