API Reference
The API reference below is generated automatically from the public cellcoloc
package and its docstrings.
Top-level package
Reusable core pipeline for interactive segmentation-based colocalization.
The package is intentionally structured so that project-specific user scripts
can stay small: they define settings, call the imported pipeline functions cell
by cell, and write all outputs to a standardized results directory located
next to the source dataset.
author: Fabrizio Musacchio date: May/June 2026
- class cellcoloc.CellposeModelConfig(model_name_or_path, segmentation_method='cellpose', diameter=None, do_3d=None, z_axis=0, channel_axis=None, cellprob_threshold=0.0, flow_threshold=0.4, anisotropy=False, flow3d_smooth=0, prefilter=None, prefilter_sigma_xy=1.0, prefilter_sigma_z=None, prefilter_median_size_xy=3, prefilter_median_size_z=None, z_crop=None, z_projection=None, threshold_percentile=98.0, threshold_background_sigma=None, threshold_min_object_voxels=10, threshold_min_hole_voxels=10, threshold_apply_closing=True, postfilters=None, min_intensity_measure='mean', min_intensity_threshold=None, local_contrast_k=1.0, local_contrast_shell_inner_radius=1, local_contrast_shell_outer_radius=4, bright_pixel_measure='count', bright_pixel_threshold=None, bright_pixel_min_count=None, bright_pixel_min_fraction=None)[source]
Bases:
objectCollect Cellpose settings for one segmentation target.
- diameter
Diameter parameter passed to
cellpose.models.CellposeModel.eval(). For Cellpose 4 and newer this can be set toNoneto let Cellpose choose its default behavior without an explicit diameter.
- model_name_or_path
Either a built-in Cellpose model identifier such as
"cyto3"or"nuclei", or a filesystem path pointing to a custom trained model.
- segmentation_method
Segmentation backend used for this channel.
"cellpose"keeps the existing neural-network workflow."otsu","li", and"percentile"use intensity thresholding followed by connected component labeling.
- do_3d
Whether Cellpose should run in 3D mode. If set to
None, the pipeline auto-detects 2D versus 3D from the loaded image z-size.
- z_axis
Array axis representing the z dimension for Cellpose.
- channel_axis
Channel axis passed to Cellpose. Keep this as
Nonefor single channel volumes.
- cellprob_threshold
Cellpose pixel probability threshold used during mask generation. This is only forwarded explicitly for Cellpose 4 and newer.
- flow_threshold
Cellpose flow error threshold used during mask generation. This is only forwarded explicitly for Cellpose 4 and newer.
- anisotropy
Controls whether a 3D Cellpose run should use anisotropy correction. Set this to
Falseto disable anisotropy handling entirely, toTrueto let the pipeline derive an anisotropy factor from the configured voxel size, or to a numeric value to force a specific Cellpose anisotropy factor. The value is ignored for 2D runs.
- flow3d_smooth
Optional Gaussian smoothing strength forwarded to Cellpose for 3D flow fields. This setting only has an effect for true 3D runs and is ignored for 2D data. Keep the default
0to disable smoothing.
- prefilter
Optional image prefilter or ordered prefilter chain applied before segmentation. Supported values are
None, a single string such as"gaussian","laplacian_of_gaussian"(alias"log"), or"median", or a sequence combining these filters in the requested execution order.
- prefilter_sigma_xy
Gaussian prefilter sigma in the in-plane directions. Used when
prefilter="gaussian".
- prefilter_sigma_z
Gaussian prefilter sigma along z. If
None, the pipeline reusesprefilter_sigma_xy. Only relevant for 3D data.
- prefilter_median_size_xy
Median prefilter kernel size in the in-plane directions. Used when
prefilter="median".
- prefilter_median_size_z
Median prefilter kernel size along z. If
None, the pipeline reusesprefilter_median_size_xy. Only relevant for 3D data.
- z_crop
Optional global z-range restriction in
(start, stop)form. When set on any participating channel config, the pipeline applies this crop consistently to all channels and all ROIs for the internal segmentation and quantification steps. The full stack is still shown in visualization outputs.
- z_projection
Optional global projection method applied along the z axis before any later ROI drawing, segmentation, quantification, or visualization. Supported values are
None(default),"max","mean","median","std", and"var". When used together withz_crop, only the cropped z interval is projected.
- threshold_percentile
Percentile used when
segmentation_method="percentile".
- threshold_background_sigma
Optional Gaussian sigma used for background subtraction before threshold-based segmentation.
- threshold_min_object_voxels
Minimum object size kept after threshold-based segmentation.
- threshold_min_hole_voxels
Minimum hole size filled after threshold-based segmentation.
- threshold_apply_closing
Whether a small binary closing step should be applied before threshold cleanup.
- postfilters
Optional post-segmentation filters applied to the resulting masks. Supported values are
None,"min_intensity","local_contrast","bright_pixel_support", or a list combining them in the requested execution order.
- min_intensity_measure
Statistic used by the
"min_intensity"postfilter. Supported values are"mean","median", and"max".
- min_intensity_threshold
Intensity threshold used by the
"min_intensity"postfilter.
- local_contrast_k
Contrast multiplier used by the
"local_contrast"postfilter in the criterionobject_median > background_median + k * background_mad.
- local_contrast_shell_inner_radius
Inner dilation radius, in pixels or voxels, used to construct the local shell for the
"local_contrast"postfilter.
- local_contrast_shell_outer_radius
Outer dilation radius, in pixels or voxels, used to construct the local shell for the
"local_contrast"postfilter.
- bright_pixel_measure
Statistic used by the
"bright_pixel_support"postfilter."count"requires at least a minimum number of bright pixels within the mask, while"fraction"requires a minimum fraction of bright pixels relative to the object size.
- bright_pixel_threshold
Intensity threshold above which a pixel or voxel counts as bright for the
"bright_pixel_support"postfilter.
- bright_pixel_min_count
Minimum number of bright pixels or voxels required when
bright_pixel_measure="count".
- bright_pixel_min_fraction
Minimum fraction of bright pixels or voxels required when
bright_pixel_measure="fraction".
- anisotropy: bool | float
- bright_pixel_measure: str
- bright_pixel_min_count: int | None
- bright_pixel_min_fraction: float | None
- bright_pixel_threshold: float | None
- cellprob_threshold: float
- channel_axis: int | None
- diameter: float | None
- do_3d: bool | None
- flow3d_smooth: int
- flow_threshold: float
- local_contrast_k: float
- local_contrast_shell_inner_radius: int
- local_contrast_shell_outer_radius: int
- min_intensity_measure: str
- min_intensity_threshold: float | None
- model_name_or_path: str
- postfilters: str | Sequence[str] | None
- prefilter: str | Sequence[str] | None
- prefilter_median_size_xy: int
- prefilter_median_size_z: int | None
- prefilter_sigma_xy: float
- prefilter_sigma_z: float | None
- segmentation_method: str
- threshold_apply_closing: bool
- threshold_background_sigma: float | None
- threshold_min_hole_voxels: int
- threshold_min_object_voxels: int
- threshold_percentile: float
- z_axis: int
- z_crop: tuple[int | None, int | None] | None
- z_projection: str | None
- class cellcoloc.ChannelConfig(cell_channel, marker_channel, optional_region_channel=None)[source]
Bases:
objectDescribe which channels should be used for the analysis.
- cell_channel
Zero-based channel index containing the larger cellular compartment that should be segmented with Cellpose, for example cytoskeleton or soma.
- marker_channel
Zero-based channel index containing the marker-positive structure that determines the colocalization class, for example nuclei or DAPI.
- optional_region_channel
Optional zero-based channel index for a third channel that is thresholded to estimate a region coverage metric, for example tumor infiltration. Set to
Noneto disable the optional third-channel analysis entirely.
- cell_channel: int
- marker_channel: int
- optional_region_channel: int | None
- class cellcoloc.ColocalizationConfig(min_cell_voxels=200, overlap_fraction_threshold=0.02, min_overlap_voxels=20, evaluate_optional_region_cell_positivity=False)[source]
Bases:
objectThresholds controlling how cell-to-marker overlap is interpreted.
- min_cell_voxels
Minimum size required for cell labels after segmentation cleanup.
- overlap_fraction_threshold
Minimum fraction of the cell mask that must overlap a marker object for the cell to be counted as positive.
- min_overlap_voxels
Minimum absolute overlap size required for positivity.
- evaluate_optional_region_cell_positivity
When
Trueand an optional third channel has been segmented, the pipeline additionally evaluates which cells overlap that third-channel segmentation. This yields separate optional-region positivity columns as well as a combined marker-and-optional-region double-positive flag.
- evaluate_optional_region_cell_positivity: bool
- min_cell_voxels: int
- min_overlap_voxels: int
- overlap_fraction_threshold: float
- class cellcoloc.ColocalizationRunResult(cell_masks, marker_masks, positive_cell_masks, tables, optional_region_masks=None, analysis_z_bounds=None, cell_refinement_context=None, marker_refinement_context=None, optional_region_refinement_context=None)[source]
Bases:
objectBundle label masks and tables generated by one completed analysis run.
- cell_masks, marker_masks, positive_cell_masks
Full-stack label images for the primary cell channel, the marker channel, and the subset of marker-positive cells.
- tables
Detailed, per-cell summary, and per-ROI overview tables.
- optional_region_masks
Optional third-channel label image when such a channel was segmented.
- analysis_z_bounds
Optional global z interval actually used for internal segmentation and quantification. Arrays remain full-stack sized even when this is set.
- cell_refinement_context, marker_refinement_context,
- optional_region_refinement_context
Optional cached Cellpose network outputs that allow later threshold-only refinement without rerunning the neural network forward pass.
- analysis_z_bounds: tuple[int, int] | None
- cell_masks: ndarray
- cell_refinement_context: CellposeChannelRefinementContext | None
- marker_masks: ndarray
- marker_refinement_context: CellposeChannelRefinementContext | None
- optional_region_masks: ndarray | None
- optional_region_refinement_context: CellposeChannelRefinementContext | None
- positive_cell_masks: ndarray
- tables: ColocalizationTables
- class cellcoloc.ColocalizationTables(detailed, summary, overview, marker_properties=None, third_channel_properties=None, roi_cell_summary=None, roi_marker_summary=None, roi_third_channel_summary=None)[source]
Bases:
objectBundle all exported multi-channel colocalization result tables.
- detailed
Per-overlap table containing one row per cell-marker overlap event.
- summary
Main per-cell colocalization table for the cell channel, augmented with cell-channel morphology metrics.
- overview
Existing per-ROI colocalization overview table. This is still exposed under the historic attribute name
overviewfor backward compatibility, even though the Excel export sheet is namedroi_coloc_overview.
- marker_properties
Per-object morphology table for the segmented marker channel.
- third_channel_properties
Optional per-object morphology table for the segmented third channel.
- roi_cell_summary
Per-ROI means of the cell-channel morphology metrics.
- roi_marker_summary
Per-ROI means of the marker-channel morphology metrics.
- roi_third_channel_summary
Optional per-ROI means of the third-channel morphology metrics.
- detailed: DataFrame
- marker_properties: DataFrame | None
- overview: DataFrame
- roi_cell_summary: DataFrame | None
- roi_marker_summary: DataFrame | None
- roi_third_channel_summary: DataFrame | None
- summary: DataFrame
- third_channel_properties: DataFrame | None
- class cellcoloc.DisplayNames(cell='Cells', marker='Marker', optional_region='Optional region', positive_cells='Marker-positive cells')[source]
Bases:
objectHuman-readable names used in napari layers and user-facing messages.
- cell: str
- marker: str
- optional_region: str
- positive_cells: str
- class cellcoloc.LoadedImageChannels(source_path, paths, voxel_scale_zyx, cell_image, marker_image, optional_region_image, raw_shape_tzcyx, raw_z_size, is_3d, metadata, analysis_z_bounds=None, z_projection_method=None)[source]
Bases:
objectStore the loaded analysis channels and related metadata.
The stored image arrays may either represent the original
ZYXchannels loaded from disk or a derived analysis view, for example a z-projection prepared before ROI drawing and segmentation.- analysis_z_bounds: tuple[int, int] | None
- cell_image: ndarray
- is_3d: bool
- marker_image: ndarray
- metadata: Any
- optional_region_image: ndarray | None
- paths: ResultsPaths
- raw_shape_tzcyx: tuple[int, ...]
- raw_z_size: int
- source_path: Path
- voxel_scale_zyx: tuple[float, float, float]
- z_projection_method: str | None
- class cellcoloc.LoadedSingleChannelImage(source_path, paths, voxel_scale_zyx, image, raw_shape_tzcyx, raw_z_size, is_3d, metadata, analysis_z_bounds=None, z_projection_method=None)[source]
Bases:
objectStore one loaded analysis channel and related metadata.
The stored image array may represent either the original
ZYXchannel loaded from disk or a derived analysis view such as a z projection.- analysis_z_bounds: tuple[int, int] | None
- image: ndarray
- is_3d: bool
- metadata: Any
- paths: SingleChannelResultsPaths
- raw_shape_tzcyx: tuple[int, ...]
- raw_z_size: int
- source_path: Path
- voxel_scale_zyx: tuple[float, float, float]
- z_projection_method: str | None
- class cellcoloc.OptionalRegionSegmentationConfig(enabled=False, method='otsu', percentile=98.0, gaussian_sigma=1.0, background_sigma=None, min_object_voxels=10, min_hole_voxels=10, apply_closing=True)[source]
Bases:
objectSettings for the optional threshold-based third-channel analysis.
The default pipeline is a two-channel colocalization problem. When
enabledis set toTrueand a third channel is configured, the pipeline additionally segments a thresholded region mask and reports its area and volume fraction inside each ROI.- apply_closing: bool
- background_sigma: float | None
- enabled: bool
- gaussian_sigma: float | None
- method: str
- min_hole_voxels: int
- min_object_voxels: int
- percentile: float
- class cellcoloc.OptionalRegionSegmentationResult(mask, labels, threshold, corrected_image)[source]
Bases:
objectHold the results of the optional third-channel segmentation.
- corrected_image: ndarray
- labels: ndarray
- mask: ndarray
- threshold: float
- class cellcoloc.ResultsPaths(source_path, results_dir, roi_mask_path, detailed_csv_path, excel_path, cell_mask_path, marker_mask_path, positive_cell_mask_path, optional_region_mask_path)[source]
Bases:
objectCollect all output locations for one input dataset.
- cell_mask_path: Path
- detailed_csv_path: Path
- excel_path: Path
- marker_mask_path: Path
- optional_region_mask_path: Path
- positive_cell_mask_path: Path
- results_dir: Path
- roi_mask_path: Path
- source_path: Path
- class cellcoloc.RuntimeConfig(draw_rois=True, process_rois=True, open_results=True, use_gpu=True, crop_for_testing=None, image_loading_mode='memory')[source]
Bases:
objectExecution-time settings that control interactivity and test crops.
- draw_rois
Whether the interactive ROI-drawing step should be used.
- process_rois
Whether ROI-wise processing should be executed.
- open_results
Whether napari result viewers should be opened.
- use_gpu
Whether GPU execution should be requested for Cellpose.
- crop_for_testing
Optional test crop in
(Z, Y, X)order.
- image_loading_mode
Controls how OMIO loads the raw microscopy file.
"memory"loads the image eagerly in memory and forwardszarr_store=Nonetoomio.imread()."memap"useszarr_store="disk"withreuse_disk_cache=Trueso large stacks can be backed by disk cache instead of being fully materialized up front.
- crop_for_testing: tuple[slice, slice, slice] | None
- draw_rois: bool
- image_loading_mode: str
- open_results: bool
- process_rois: bool
- use_gpu: bool
- class cellcoloc.SingleChannelAnalysisConfig(min_object_voxels=50)[source]
Bases:
objectAnalysis thresholds for one-channel object counting workflows.
- min_object_voxels
Minimum size required for segmented objects after ROI-wise segmentation and before object counting or occupancy calculation.
- min_object_voxels: int
- class cellcoloc.SingleChannelConfig(channel_index)[source]
Bases:
objectDescribe a one-channel segmentation workflow.
- channel_index
Zero-based channel index that should be loaded and segmented. This lightweight config is used by CellColoc’s optional single-channel workflow, which reuses the same segmentation, ROI, projection, filtering, and refinement backends as the multi-channel pipeline but skips all colocalization logic.
- channel_index: int
- class cellcoloc.SingleChannelDisplayNames(channel='Channel', objects='Segmented objects')[source]
Bases:
objectHuman-readable names used in one-channel napari visualizations.
- channel: str
- objects: str
- class cellcoloc.SingleChannelResultsPaths(source_path, results_dir, roi_mask_path, object_csv_path, excel_path, mask_path)[source]
Bases:
objectCollect all output locations for one single-channel dataset run.
- excel_path: Path
- mask_path: Path
- object_csv_path: Path
- results_dir: Path
- roi_mask_path: Path
- source_path: Path
- class cellcoloc.SingleChannelRunResult(masks, tables, analysis_z_bounds=None, refinement_context=None)[source]
Bases:
objectBundle masks and tables generated by one single-channel analysis run.
- masks
Full-stack label image for the segmented objects of the analyzed channel.
- tables
Per-object and per-ROI summary tables.
- analysis_z_bounds
Optional global z interval used internally for segmentation and quantification. Arrays remain full-stack sized even when this is set.
- refinement_context
Optional cached Cellpose network outputs that allow later threshold-only refinement without rerunning the neural network forward pass.
- analysis_z_bounds: tuple[int, int] | None
- masks: ndarray
- refinement_context: CellposeChannelRefinementContext | None
- tables: SingleChannelTables
- class cellcoloc.SingleChannelTables(objects, voxel_plausibility, overview)[source]
Bases:
objectBundle tables produced by one-channel analyses.
- objects
Main per-object summary table containing biologically meaningful size and shape descriptors such as area, volume, surface area, roundness, or sphericity, depending on whether the analysis view is effectively 2D or 3D.
- voxel_plausibility
Technical cross-check table comparing direct voxel counts against
regionprops-derived voxel counts for each object.
- overview
Per-ROI overview table containing object counts, occupancy metrics, and per-ROI means of the object-summary shape descriptors.
- objects: DataFrame
- overview: DataFrame
- voxel_plausibility: DataFrame
- cellcoloc.analyze_existing_masks(loaded_images, roi_labels_2d, cell_masks, marker_masks, colocalization_config, optional_region_result=None, optional_region_masks=None, analysis_z_bounds=None, cell_refinement_context=None, marker_refinement_context=None, optional_region_refinement_context=None, cell_model_config=None, marker_model_config=None, optional_region_model_config=None)[source]
Recompute colocalization tables from existing label masks.
This helper is used both after the initial Cellpose segmentation and after any later manual or threshold-based refinement of the label masks.
- Parameters:
loaded_images – Loaded raw analysis channels and dataset metadata.
roi_labels_2d – Drawn or generated 2D ROI label mask.
cell_masks, marker_masks – Full-stack label masks for the two primary analysis channels. They may originate from Cellpose, thresholding, or manual relabeling.
colocalization_config – Thresholds controlling how per-cell overlaps are interpreted.
optional_region_result, optional_region_masks – Optional third-channel segmentation supplied either as the legacy result wrapper or directly as a label image. When both are provided,
optional_region_maskstakes precedence.analysis_z_bounds – Optional global z interval used for the current analysis. Labels outside this interval are ignored internally but the stored masks keep full-stack shape.
cell_refinement_context, marker_refinement_context – Optional cached Cellpose network outputs used for later threshold-only refinement.
cell_model_config, marker_model_config, optional_region_model_config – Optional channel configs reused here mainly so postfilters can be applied consistently when masks are reanalyzed.
- Return type:
- Returns:
ColocalizationRunResult – Structured masks and tables reflecting the provided segmentation state.
- cellcoloc.analyze_existing_single_channel_masks(loaded_image, roi_labels_2d, masks, analysis_config, analysis_z_bounds=None, refinement_context=None, model_config=None)[source]
Recompute object tables from existing one-channel label masks.
- Return type:
- cellcoloc.build_positive_cell_mask(cell_masks, summary_table)[source]
Create a label image containing only marker-positive cells.
The returned label image preserves the original cell labels for all cells classified as marker-positive in
summary_tableand sets every other voxel to zero.- Return type:
ndarray
- cellcoloc.build_results_paths(source_path)[source]
Create the standard results paths for one microscopy dataset.
- Parameters:
source_path – Path to the raw microscopy file.
- Return type:
- Returns:
ResultsPaths – Structured output paths inside a
resultssubdirectory located next to the raw input file.
- cellcoloc.build_single_channel_results_paths(source_path)[source]
Create the standard results paths for one single-channel dataset run.
- Return type:
- cellcoloc.create_cellpose_model(model_name_or_path, use_gpu)[source]
Create a Cellpose model from either a built-in name or a custom path.
The helper is intentionally strict: if a requested built-in model name is not locally available in the installed Cellpose version, it raises a clear error instead of silently falling back to a different model. It also adapts model construction to the installed Cellpose major version so that newer Cellpose 4 setups do not receive the deprecated
model_typeargument.- Return type:
CellposeModel
- cellcoloc.create_cellpose_models_for_channels(cell_model_config, marker_model_config, use_gpu)[source]
Create Cellpose model instances for the cell and marker channels.
Models are only created for channels configured with
segmentation_method="cellpose". For Cellpose 4 and newer, the same model instance is reused when both such channels request the same built-in model or custom model path. For older Cellpose versions, the previous behavior is preserved and separate model instances are created for each Cellpose channel configuration.- Return type:
tuple[CellposeModel|None,CellposeModel|None]
- cellcoloc.create_full_image_roi_labels(image_shape_yx)[source]
Create a single ROI label covering the complete field of view.
This helper is useful for analyses that should be run on the entire image without manual ROI drawing. The returned label image contains the label value
1everywhere.- Return type:
ndarray
- cellcoloc.create_roi_drawing_viewer(loaded_images, display_names=None)[source]
Open a napari viewer for drawing 2D ROIs on max projections.
- cellcoloc.create_single_channel_roi_drawing_viewer(loaded_image, display_names=None)[source]
Open a napari viewer for drawing 2D ROIs on one-channel projections.
- cellcoloc.evaluate_cellpose_model(model, image_zyx, model_config, voxel_scale_zyx)[source]
Run Cellpose and return the resulting label image as
uint32.The function accepts both 3D
ZYXarrays and 2D images represented as a singleton-z(1, Y, X)volume. Whenmodel_config.do_3disNone, the function auto-detects the correct Cellpose mode from the z-size.- Return type:
tuple[ndarray,CellposeRefinementRoiCache|None]
- cellcoloc.export_analysis_outputs(run_result, paths, optional_region_result=None)[source]
Write all standard tables and masks for one completed analysis run.
- Parameters:
run_result – Completed Cellpose colocalization result bundle.
paths – Standardized output paths created for the current dataset.
optional_region_result – Optional third-channel segmentation result. When provided, the labeled mask is exported alongside the main colocalization outputs.
- Return type:
None
- cellcoloc.export_single_channel_outputs(run_result, paths)[source]
Write standard tables and masks for one completed single-channel run.
The Excel workbook contains three sheets:
object_summaryfor biologically relevant size and shape metricsvoxel_plausibility_checkfor technical voxel-count cross-checksroi_overviewfor ROI-level counts, occupancies, and mean metrics
- Return type:
None
- cellcoloc.extract_label_masks_from_viewer(viewer, cell_layer_name='Cellpose cell masks', marker_layer_name='Cellpose marker masks')[source]
Extract the current cell and marker label layers from a napari viewer.
This is primarily used after manual label editing so the modified napari layers can be fed back into
cellcoloc.analysis.analyze_existing_masks().- Return type:
tuple[ndarray,ndarray]
- cellcoloc.extract_single_channel_masks_from_viewer(viewer, object_layer_name='Segmented objects')[source]
Extract the current one-channel labels layer from a napari viewer.
- Return type:
ndarray
- cellcoloc.filter_labels_by_size(label_image, min_size)[source]
Remove labels smaller than the configured voxel threshold.
- Return type:
ndarray
- cellcoloc.get_available_cellpose_model_names()[source]
Return locally available built-in and user-registered Cellpose models.
- Return type:
list[str]
- cellcoloc.get_bbox_2d(mask_2d)[source]
Return the bounding box slices of a 2D binary mask.
- Return type:
tuple[slice,slice] |None
- cellcoloc.get_cellpose_major_version()[source]
Return the installed Cellpose major version when it can be determined.
- Return type:
int|None
- cellcoloc.get_roi_label_points(roi_labels_2d)[source]
Return ROI centroids and text labels for napari point annotations.
- Return type:
tuple[ndarray,list[str]]
- cellcoloc.get_runtime_cache_root()[source]
Return the temporary fallback directory used for runtime caches.
The directory itself is only used when one of the default library cache or config locations turns out to be unavailable for writing.
- Return type:
Path
- cellcoloc.load_analysis_images(source_path, channel_config, voxel_scale_zyx, crop_for_testing=None, image_loading_mode='memory')[source]
Load the configured channels from a microscopy dataset.
The function relies on
omioso that future projects are not limited to CZI files. The loaded channels are returned asZYXvolumes. Two loading modes are supported:"memory": eager in-memory loading withzarr_store=None"memap": disk-backed OMIO/Zarr cache withzarr_store="disk"andreuse_disk_cache=True
- Parameters:
source_path – Input microscopy dataset that OMIO can open.
channel_config – Zero-based channel mapping defining which raw channels correspond to the cell, marker, and optional third channel.
voxel_scale_zyx – Optional explicit voxel size in micrometers. This may be passed either in full
(Z, Y, X)order or, for 2D convenience, as(Y, X). A two-value input is internally expanded to(1.0, Y, X). When this argument isNone, the loader first tries to derive physical pixel sizes from OMIO metadata entries such asPhysicalSizeZand falls back to(1.0, 1.0, 1.0)with a warning when no usable metadata are available.crop_for_testing – Optional test crop applied after channel extraction in
(Z, Y, X)order.image_loading_mode – Raw-image loading strategy.
"memory"materializes the full image eagerly, whereas"memap"keeps OMIO’s disk-backed Zarr cache.
- Return type:
- Returns:
LoadedImageChannels – Structured bundle containing the extracted analysis channels, resolved voxel size, OMIO metadata, and standardized output paths.
- cellcoloc.load_roi_labels(path)[source]
Load a previously saved 2D ROI label mask.
- Return type:
ndarray
- cellcoloc.load_single_channel_image(source_path, channel_config, voxel_scale_zyx, crop_for_testing=None, image_loading_mode='memory')[source]
Load one configured analysis channel from a microscopy dataset.
- Parameters:
source_path – Input microscopy dataset that OMIO can open.
channel_config – One-channel mapping defining which raw channel should be analyzed.
voxel_scale_zyx – Optional explicit voxel size in micrometers, either as
(Z, Y, X)or, for 2D convenience, as(Y, X).crop_for_testing – Optional test crop applied after channel extraction in
(Z, Y, X)order.image_loading_mode – Raw-image loading strategy.
"memory"materializes the full image eagerly, whereas"memap"keeps OMIO’s disk-backed Zarr cache.
- Return type:
- cellcoloc.prepare_loaded_images_for_analysis(loaded_images, *model_configs)[source]
Prepare a loaded dataset for downstream analysis according to configs.
This helper currently resolves an optional global z-projection from the provided channel configs. When no projection method is configured, the original
loaded_imagesobject is returned unchanged. When a projection is requested, the helper optionally applies the globally configured z-crop first, projects every available channel along z, and returns a newLoadedImageChannelsbundle that behaves like a 2D dataset with singleton-z image arrays. All later ROI drawing, segmentation, quantification, and visualization steps should use this prepared bundle.- Parameters:
loaded_images – Previously loaded channel bundle from
cellcoloc.io.load_analysis_images().*model_configs – One or more participating channel configs. Any configured
z_cropandz_projectionvalues are resolved globally across them.
- Return type:
- Returns:
LoadedImageChannels – Either the original loaded image bundle or a projected analysis view.
- cellcoloc.prepare_loaded_single_channel_image_for_analysis(loaded_image, model_config)[source]
Prepare one loaded channel for downstream analysis according to config.
When
model_config.z_projectionis set, the helper optionally applies the corresponding globalz_cropfirst, then projects the image along z, and returns a singleton-z 2D analysis view.- Return type:
- cellcoloc.prepare_runtime_environment()[source]
Prepare optional fallback cache locations for desktop library imports.
The function checks whether the usual per-user config and cache locations for Matplotlib, napari, and related tooling are writable. Only if a path is unavailable will it redirect the corresponding environment variable to a temporary fallback under the system temp directory.
- Return type:
dict[str,str]- Returns:
dict[str, str] – Mapping of environment variables that were redirected to fallback paths. An empty mapping means the default user locations were usable.
- cellcoloc.rasterize_shapes_to_labelmask(shapes_layer, image_shape_yx, scale_yx=(1.0, 1.0))[source]
Rasterize napari polygon-like shapes into a 2D label mask.
Napari stores shape coordinates in world coordinates when image layers use a physical scale. The coordinates are therefore mapped back to pixel coordinates before rasterization.
- Return type:
ndarray
- cellcoloc.refine_run_result_from_cellpose_cache(loaded_images, roi_labels_2d, run_result, colocalization_config, cell_model_config=None, marker_model_config=None, optional_region_model_config=None, cell_cellprob_threshold=None, cell_flow_threshold=None, marker_cellprob_threshold=None, marker_flow_threshold=None, optional_region_cellprob_threshold=None, optional_region_flow_threshold=None, optional_region_result=None)[source]
Recompute masks and tables from cached Cellpose outputs.
This avoids rerunning the neural network forward pass and only recomputes the mask generation stage from cached
dPandcellprobarrays. Passingcell_model_config=None,marker_model_config=None, and/oroptional_region_model_config=Noneleaves the respective channel unchanged and reuses the masks already stored inrun_result.Any z-crop defined in the supplied refinement configs is interpreted as one global analysis z range and applied consistently across all channels. When no refinement config specifies a z-crop, the function preserves the z-bounds stored in
run_result. When the loaded images already represent a z-projection, additional z-cropping is ignored because the data have already been collapsed to a singleton-z analysis view.- Return type:
- cellcoloc.refine_single_channel_run_result_from_cellpose_cache(loaded_image, roi_labels_2d, run_result, analysis_config, model_config=None, cellprob_threshold=None, flow_threshold=None)[source]
Recompute one-channel masks and tables from cached Cellpose outputs.
Passing
model_config=Noneleaves the current masks unchanged and simply rebuilds the object tables from the masks already stored inrun_result.- Return type:
- cellcoloc.relabel_with_offset(mask, offset)[source]
Shift all non-zero labels by a fixed offset.
- Return type:
ndarray
- cellcoloc.run_roi_cellpose_colocalization(loaded_images, roi_labels_2d, cell_model_config, marker_model_config, colocalization_config, runtime_config, optional_region_model_config=None, optional_region_result=None)[source]
Run the configured ROI-wise segmentation workflow and build result tables.
The pipeline always segments ROI crops in
XYand may additionally apply one global analysis z-crop resolved from the participating channel configs. That z-crop affects all channels, all ROIs, and all downstream quantification consistently, while the exported and visualized arrays keep full-stack shape. When the inputloaded_imagesbundle already represents a prepared z-projection, segmentation and quantification operate on that projected 2D analysis view instead of the original full stack.The two primary analysis channels can each use either Cellpose or one of the supported threshold-based backends. An optional third channel can be segmented through the same mechanism and contributes occupancy metrics, and optionally per-cell positivity, to the result tables.
- Return type:
- cellcoloc.run_roi_single_channel_segmentation(loaded_image, roi_labels_2d, model_config, analysis_config, runtime_config)[source]
Run ROI-wise segmentation and object counting for one analysis channel.
- Return type:
- cellcoloc.save_roi_labels(path, roi_labels_2d)[source]
Persist a 2D ROI label mask as
uint16TIFF.- Return type:
None
- cellcoloc.save_roi_labels_from_shapes(shapes_layer, output_path, image_shape_yx, scale_yx)[source]
Rasterize drawn ROIs and save them to the standard TIFF file.
- Return type:
ndarray
- cellcoloc.segment_optional_region(image_zyx, roi_labels_2d, config)[source]
Threshold an optional third channel and compute a cleaned 3D mask.
The function keeps the old prototype behavior while avoiding the deprecated scikit-image arguments by mapping strict minimum thresholds to the new inclusive
max_sizesemantics.- Return type:
- cellcoloc.show_analysis_results(loaded_images, roi_labels_2d, run_result, display_names=None, optional_region_result=None, viewer=None, layers_to_show=None, replace_existing_layers=True, show_optional_region_image=False)[source]
Display or refresh analysis layers in napari.
- Parameters:
layers_to_show – Optional list of logical layer keys to add or refresh. Supported keys are
"cell_image","marker_image","optional_region_image","optional_region_labels","rois","roi_numbers","cell_masks","marker_masks", and"positive_cells". WhenNone, the function renders all standard analysis layers.replace_existing_layers – If
True, existing layers with the same name are removed and added again. This keeps repeated refinement runs from piling up duplicate layers in the same viewer.show_optional_region_image – If
True, the optional third-channel image is shown even when no threshold result object is provided.
Notes
Raw image layers are always shown as the full stack. When
run_result.analysis_z_boundsis set, only the ROI label layer is visually restricted to that z interval so the viewer reflects the active analysis extent without hiding the surrounding image context.
- cellcoloc.show_optional_region_segmentation(loaded_images, region_result, roi_labels_2d=None, display_names=None, viewer=None)[source]
Display the optional third-channel segmentation in napari.
This helper is mainly intended for standalone inspection of threshold- or Cellpose-based third-channel masks. ROI overlays are shown across the full stack because no run-specific analysis z-crop is available in this interface.
- cellcoloc.show_single_channel_results(loaded_image, roi_labels_2d, run_result, display_names=None, viewer=None, layers_to_show=None, replace_existing_layers=True)[source]
Display or refresh one-channel analysis layers in napari.
Supported
layers_to_showkeys are"channel_image","rois","roi_numbers", and"masks".
- cellcoloc.try_load_roi_labels(path)[source]
Load a saved 2D ROI label mask when it exists.
- Parameters:
path – Expected path of the ROI label TIFF.
- Return type:
ndarray|None- Returns:
np.ndarray | None – The loaded ROI label mask when the file exists, otherwise
None. This helper is useful for interactive scripts that should prefer a previously drawn ROI mask but fall back to manual drawing when no saved mask is available yet.
Public API overview
|
Collect Cellpose settings for one segmentation target. |
|
Describe which channels should be used for the analysis. |
|
Thresholds controlling how cell-to-marker overlap is interpreted. |
|
Human-readable names used in napari layers and user-facing messages. |
|
Settings for the optional threshold-based third-channel analysis. |
|
Execution-time settings that control interactivity and test crops. |
|
Collect all output locations for one input dataset. |
|
Store the loaded analysis channels and related metadata. |
|
Hold the results of the optional third-channel segmentation. |
|
Bundle all exported multi-channel colocalization result tables. |
|
Bundle label masks and tables generated by one completed analysis run. |
|
Create the standard results paths for one microscopy dataset. |
|
Load the configured channels from a microscopy dataset. |
|
Persist a 2D ROI label mask as |
|
Load a previously saved 2D ROI label mask. |
|
Load a saved 2D ROI label mask when it exists. |
|
Write all standard tables and masks for one completed analysis run. |
|
Recompute colocalization tables from existing label masks. |
Prepare a loaded dataset for downstream analysis according to configs. |
|
Prepare optional fallback cache locations for desktop library imports. |
|
Return the temporary fallback directory used for runtime caches. |
|
|
Create a single ROI label covering the complete field of view. |
|
Rasterize napari polygon-like shapes into a 2D label mask. |
|
Open a napari viewer for drawing 2D ROIs on max projections. |
|
Rasterize drawn ROIs and save them to the standard TIFF file. |
|
Return the bounding box slices of a 2D binary mask. |
|
Return ROI centroids and text labels for napari point annotations. |
|
Create a Cellpose model from either a built-in name or a custom path. |
Create Cellpose model instances for the cell and marker channels. |
|
|
Run Cellpose and return the resulting label image as |
|
Shift all non-zero labels by a fixed offset. |
|
Remove labels smaller than the configured voxel threshold. |
Return the installed Cellpose major version when it can be determined. |
|
Return locally available built-in and user-registered Cellpose models. |
|
|
Threshold an optional third channel and compute a cleaned 3D mask. |
|
Run the configured ROI-wise segmentation workflow and build result tables. |
|
Recompute masks and tables from cached Cellpose outputs. |
|
Create a label image containing only marker-positive cells. |
|
Extract the current cell and marker label layers from a napari viewer. |
|
Display the optional third-channel segmentation in napari. |
|
Display or refresh analysis layers in napari. |