spacr.spacr_cellpose

Workflow inputs and outputs

Mask the whole folder

Apply the selected segmentation model to the open image folder through Make Masks; inspect saved labels before measuring them.

Open: Make Masks → Mask the whole folder.

Inputs and outputs below include conditional alternatives. The guidance and handoff notes say which route applies.

Inputs

  • Microscope images — Source image folder; original files, supported vendor files or imported TIFFs.

  • Segmentation checkpoint — Saved Cellpose-compatible checkpoint or a compatible installed backend selected with its own configuration.

Outputs

  • Label masks — masks/ when retained, or explicitly saved image/mask pairs. Intermediate masks may be removed by cleanup.

API reference.

Module tutorial.

Direct Cellpose mask generation

Run a stock or custom Cellpose model on TIFF fields through the Python API. Despite its historical identify_masks_finetune name, this function performs inference, not training. Review normalization, channels, resizing and model parameters; masks are written only when save is enabled. Import compatible image/mask pairs through External Masks before Measure, or curate the pairs before training. This call does not build a Measure-ready merged project.

Use from Python: spacr.spacr_cellpose.identify_masks_finetune(). This API-only workflow has no Home tile or menu entry.

Inputs and outputs below include conditional alternatives. The guidance and handoff notes say which route applies.

Inputs

  • TIFF fields for direct Cellpose inference — Top-level, lowercase .tif files in src; existing same-name files in src/masks are skipped. Supply the configured channels and a compatible stock model_name or custom_model checkpoint.

  • Segmentation checkpoint — Saved Cellpose-compatible checkpoint or a compatible installed backend selected with its own configuration.

Outputs

  • Direct Cellpose TIFF masks — When save=True, src/masks/<image-name>.tif contains integer labels. The call returns None and does not produce merged arrays or measurements.db.

Before this module

  • Cellpose Workbench: Pass the trained checkpoint as custom_model with the matching image channels and preprocessing.

After this module

  • External Masks: Provide the saved label TIFFs and their original images to External Masks, assign object roles and create the merged project before Measure.

API reference.

Cellpose model evaluation and mask-generation workflows.

Functions

cellpose_channel_axis(stack)

Return the channel_axis Cellpose 4 accepts for one loaded image.

cellpose_rescale(value)

The rescale= Cellpose should actually receive. Falsy becomes None.

check_cellpose_models(settings)

Run each stock Cellpose model over settings['src'] for side-by-side comparison.

display(*args, **kwargs)

Discard display payloads when IPython's helper is unavailable.

generate_masks_from_imgs(src, model, model_name, ...)

Run a Cellpose model over every .tif in src and optionally save masks.

identify_masks_finetune(settings)

Generate Cellpose masks for a directory of images using a stock or custom model.

parse_cellpose4_output(output)

Normalize the return value of CellposeModel.eval into per-image flow lists.

Module Contents

spacr.spacr_cellpose.cellpose_channel_axis(stack)[source]

Return the channel_axis Cellpose 4 accepts for one loaded image.

cellpose.transforms.convert_image — which CellposeModel.eval calls with whatever channel_axis it was handed — indexes x.shape[channel_axis] and rejects a non-None axis outright for a 2-D input. The two shapes spaCR’s loaders produce are therefore both illegal under the old hard-coded channel_axis=3:

  • (H, W, C) -> IndexError: tuple index out of range (there is no axis 3 on a 3-D array; the channel axis is 2, i.e. -1).

  • (H, W) -> ValueError: 2D image provided, but channel_axis is not None.

object.py already passes channel_axis=-1 because it only ever hands Cellpose channels-last stacks. The functions here also serve greyscale images (_load_*_images_and_labels squeezes a single-channel load down to 2-D), so the axis has to be chosen per image.

Parameters:

stack – One image as loaded by spacr.io, either (H, W) or channels-last (H, W, C).

Returns:

-1 for a channels-last stack, None for a 2-D image.

spacr.spacr_cellpose.cellpose_rescale(value)[source]

The rescale= Cellpose should actually receive. Falsy becomes None.

rescale was DEPRECATED-AND-IGNORED in Cellpose 4.0, so spaCR passing False cost nothing and nobody noticed the type was wrong. Cellpose 4.2 reads it again:

niter_scale = 1 if rescale is None or not resample else rescale
niter = int(200/niter_scale) if niter is None or niter == 0 else niter

With rescale=False and resample=True – spaCR’s shipped rescale default, and a resample a user is entirely likely to turn on – niter_scale becomes False and the second line reads int(200/False): ZeroDivisionError, raised from inside Cellpose, on a settings combination both GUIs offer.

None is Cellpose’s own spelling of “not set” and takes the niter_scale = 1 branch, which is what False was always meant to mean here. 0 goes the same way, for the same reason.

Parameters:

value – whatever the settings carry for rescale.

Returns:

None for a falsy value, otherwise the value unchanged.

spacr.spacr_cellpose.check_cellpose_models(settings)[source]

Run each stock Cellpose model over settings['src'] for side-by-side comparison.

Parameters:

settings – Settings dict; canonicalized via spacr.settings.get_check_cellpose_models_default_settings().

Returns:

None.

spacr.spacr_cellpose.display(*args, **kwargs)[source]

Discard display payloads when IPython’s helper is unavailable.

spacr.spacr_cellpose.generate_masks_from_imgs(src, model, model_name, batch_size, diameter, cellprob_threshold, flow_threshold, grayscale, save, normalize, channels, percentiles, invert, plot, resize, target_height, target_width, remove_background, background, Signal_to_noise, verbose)[source]

Run a Cellpose model over every .tif in src and optionally save masks.

Batches the workload and writes results to <src>/<model_name>.

Parameters:
  • src – Directory containing input .tif images.

  • model – Instantiated cellpose.models.CellposeModel.

  • model_name – Model identifier; names the output subdirectory. It no longer selects a channel pair — Cellpose 4 deprecated eval(channels=...), so the pre-SAM cyto/cyto2/nucleus channel conventions had no effect on the network’s input.

  • batch_size – Number of images loaded per iteration.

  • diameter – Estimated object diameter in pixels.

  • cellprob_threshold – Cell probability threshold passed to Cellpose.

  • flow_threshold – Flow error threshold passed to Cellpose.

  • grayscale – When True, force single-channel input.

  • save – When True, write masks under <src>/<model_name>.

  • normalize – When True, load images with normalization/background pipeline.

  • channels – Channel indices used when loading images.

  • percentiles – Percentile clipping range applied during normalization.

  • invert – When True, invert intensities during load.

  • plot – When True, display mask/flow diagnostics per image.

  • resize – When True, resize inputs to (target_height, target_width).

  • target_height – Target height for resized inputs.

  • target_width – Target width for resized inputs.

  • remove_background – When True, subtract background during normalization.

  • background – Background value used when remove_background is set.

  • Signal_to_noise – Minimum SNR threshold for retained signal.

  • verbose – When True, print Cellpose settings to the console.

Returns:

None.

spacr.spacr_cellpose.identify_masks_finetune(settings)[source]

Generate Cellpose masks for a directory of images using a stock or custom model.

Iterates in batches, optionally normalizing and resizing the inputs, writes the resulting masks under <src>/masks, and prints per-image progress.

Parameters:

settings – Settings dict; canonicalized via spacr.settings.get_identify_masks_finetune_default_settings(). Must contain src, model_name (or custom_model), and standard Cellpose parameters (diameter, flow_threshold, CP_prob, …).

Returns:

None.

spacr.spacr_cellpose.parse_cellpose4_output(output)[source]

Normalize the return value of CellposeModel.eval into per-image flow lists.

Accepts both the batched format (4 stacked arrays) and the per-image list format so downstream code can iterate uniformly.

Parameters:

output – Raw (masks, flows, ...) tuple returned by Cellpose.

Returns:

Tuple (masks, flows0, flows1, flows2, flows3) with per-image entries.

Raises:

ValueError – When the flows structure does not match a known layout.