spacr.object

Object segmentation, filtering, mask generation, and post-processing.

Functions

display(*args, **kwargs)

Discard display payloads when IPython's helper is unavailable.

generate_cellpose_masks(src, settings, object_type)

Segment one object channel across all .npz batches under src using a chosen Cellpose model.

generate_cellpose_masks_sam(src, settings, object_type, *)

Segment one object channel across all .npz batches under src using Cellpose-SAM.

generate_organelle_masks_sam(src, settings, object_type)

Generate organelle masks using one of several morphology-aware strategies.

merge_split_filter_masks(masks, intensity_images, ...)

Merge by perimeter and filter each in-memory field's objects.

Module Contents

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

Discard display payloads when IPython’s helper is unavailable.

spacr.object.generate_cellpose_masks(src, settings, object_type)[source]

Segment one object channel across all .npz batches under src using a chosen Cellpose model.

Selects the model via spacr.utils._choose_model() (stock or custom), runs per-batch inference with the object-specific channel/threshold settings, applies spacr.utils._filter_cp_masks(), optionally tracks timelapse objects, and writes .npy masks plus per-object counts.

Whole-plate motility analysis runs through spacr.core.preprocess_generate_masks() after frame merging, rather than within this per-object generator.

Parameters:
Returns:

None.

spacr.object.generate_cellpose_masks_sam(src, settings, object_type, *, batch_paths=None, on_batch_done=None, run_qc=True)[source]

Segment one object channel across all .npz batches under src using Cellpose-SAM.

Loads the cpsam pretrained model — or, when <object_type>_model_name (or pathogen_model) names a checkpoint the user trained, that checkpoint — iterates over each pre-batched .npz file, applies perimeter merging and area/border filtering to 2-D masks, and optionally filters objects by their absolute mean intensity in the original own-channel image. It then optionally tracks timelapse objects, saves per-image .npy masks, and records per-object counts to the run’s SQLite database. Time-stack archives must contain one filename per timepoint, regardless of the declared time-axis position; each raw filename identifies that timepoint’s (Z, Y, X, C) volume, or its (Y, X, C) image for a flat TYX series. Whole-plate motility analysis belongs to spacr.core.preprocess_generate_masks() after all object masks have been merged with their images; this generator does not run it.

An object whose model setting reads cellpose3:<model or weights path>, or any object when segmentation_backend is 'cellpose3', is segmented by _cellpose3_masks in the Cellpose 3 backend’s own environment; what it returns enters the same lines as a Cellpose-SAM result, so the saved masks and the database rows are written the same. One whose model setting reads cellpose_dino:<checkpoint path> is segmented by the Cellpose-DINO backend’s worker, which takes the very eval call a Cellpose-SAM model takes and returns its shapes. So is one whose model setting carries a StarDist, InstanSeg or Omnipose prefix (stardist:<model> and the rest), each in its own backend’s worker.

Parameters:
  • src – Directory containing the pre-batched .npz image stacks.

  • settings – Pipeline settings dict; canonicalized via spacr.settings.set_default_settings_preprocess_generate_masks().

  • object_type – 'cell', 'nucleus', 'pathogen' or 'organelle'; drives channel/threshold lookups and output folder name.

  • batch_paths – optional exclusive worker assignment of NPZ paths under src. One model is reused across the assignment; None keeps the ordinary whole-directory run. An empty assignment loads no model.

  • on_batch_done – optional callable receiving the archive path after its selected fields have completed. Failed archives are not reported.

  • run_qc – False lets a parallel coordinator run shared QC once after every worker finishes, instead of writing reports from each worker.

Returns:

None.

spacr.object.generate_organelle_masks_sam(src, settings, object_type)[source]

Generate organelle masks using one of several morphology-aware strategies.

Supported morphology modes and backends:

  • spots: punctate structures (lipid droplets, vesicles, peroxisomes) via otsu, adaptive, log, dog, cellpose.

  • network: filamentous/reticular structures (mitochondria, microtubules, ER tubules) via otsu, adaptive, ridge, hysteresis, cellpose, unet.

  • irregular: irregular-shaped organelles (Golgi, ER cisternae, lysosomes) via otsu, adaptive, cellpose.

  • ring: hollow/ring-shaped structures (endosomes, autophagosomes) via otsu, adaptive, dog, log, cellpose.

Parameters:
  • src – Path to the mask source directory containing .npz stacks.

  • settings – Configuration dict. Organelle-specific keys are prefixed with organelle_ and are documented in _set_organelle_defaults.

  • object_type – Object label (typically 'organelle'); drives the output folder name <object_type>_mask_stack.

Returns:

None. Masks are written as .npy files in <src>/<object_type>_mask_stack/.

spacr.object.merge_split_filter_masks(masks, intensity_images, settings, object_type, batch_filenames=None)[source]

Merge by perimeter and filter each in-memory field’s objects.

Skips work when no operation is enabled for object_type; otherwise processes each FOV serially so progress reporting stays in order.

Parameters:
  • masks – 2D/3D ndarray or iterable of masks (one per field).

  • intensity_images – Original own-channel arrays matching the masks, required only when an intensity bound is enabled. For channel-last batches the first channel must be the object’s own channel.

  • settings – Dict of pipeline settings; per-object-type suffixes control perimeter merging, min/max area, border removal and min/max intensity. Intensity bounds compare whole-object means in original image units; equality is retained and 0 disables each bound independently.

  • object_type – Label used to look up per-object settings ('cell', 'nucleus', 'pathogen', 'organelle').

  • batch_filenames – Optional per-FOV filenames used only for logging.

Returns:

Original masks unchanged when no operation is enabled, else a list of filtered mask arrays (one per FOV).

Nested helpers

_cellpose_z_segment_fn._segment(array, do_3D=False, anisotropy=None, z_axis=None, stitch=False)

Return labels from a 3-D, plane-list, or single-plane Cellpose call.

spacr/object.py:730

merge_split_filter_masks._progress(fov_idx, total_fovs, duration, op)

Record a per-FOV duration and emit the shared progress line.

spacr/object.py:409

merge_split_filter_masks._run_one(idx, mask, intensity_img)

Run the configured filter pipeline against a single FOV mask.

spacr/object.py:421