Segmentation (sphero_vem.segmentation)#

Two segmentation backends: Cellpose-SAM for cells and nuclei, and an empirical Bayes EM approach for nanoparticles.

Cellpose#

Cell and nucleus segmentation with Cellpose-SAM

class sphero_vem.segmentation.cellpose.core.CellposeFlowConfig(root_path, model, spacing_dir, out_path=None, verbose=True, zarr_chunks=None, batch_size=64, flow3D_smooth=2, augment=False, tile_overlap=0.3, median_filter_cellprob=False, median_filter_size=3, decompose_flows=False, decompose_flows_pad_fraction=0.3, guided_filter_cellprob=False, guided_filter_radius=8, guided_filter_eps=0.01, save_raw_flows=False)[source]#

Bases: BaseConfig

Configuration for Cellpose flow computation on a Zarr volume stack.

Parameters:
  • root_path (Path) – Root directory of the Zarr archive.

  • model (str) – Model identifier. Use "cpsam" for the pretrained Cellpose-SAM model, or a path-encoded custom model name.

  • spacing_dir (str) – Spacing directory name used to locate the source image array (e.g. "100-100-100").

  • out_path (Path | None, optional) – Output Zarr root path. If None, writes under root_path.

  • verbose (bool, optional) – Enable progress messages. Default is True.

  • zarr_chunks (tuple[int] | None, optional) – Chunk shape for output arrays. If None, inherits source chunks.

  • batch_size (int, optional) – Inference batch size. Default is 64.

  • flow3D_smooth (int, optional) – Gaussian smoothing iterations applied to 3D flows. Default is 2.

  • augment (bool, optional) – Enable test-time augmentation. Default is False.

  • tile_overlap (float, optional) – Fraction of overlap between inference tiles. Default is 0.3.

  • median_filter_cellprob (bool, optional) – Apply a 3D median filter to the cellprob map. Default is False.

  • median_filter_size (int, optional) – Kernel size for the median filter. Default is 3.

  • decompose_flows (bool, optional) – Apply Helmholtz-Hodge flow decomposition. Default is False.

  • decompose_flows_pad_fraction (float, optional) – Z-padding fraction for flow decomposition. Default is 0.3.

  • guided_filter_cellprob (bool, optional) – Apply a guided filter to the cellprob map. Default is False.

  • guided_filter_radius (int, optional) – Half-window radius for the guided filter. Default is 8.

  • guided_filter_eps (float, optional) – Regularization parameter for the guided filter. Default is 1e-2.

  • save_raw_flows (bool, optional) – Save unprocessed flows alongside processed ones. Default is False.

sphero_vem.segmentation.cellpose.core.compute_raw_flows(config)[source]#

Compute raw cellpose flows without postprocessing.

This function performs model inference only, returning the raw displacement field and cell probability. No postprocessing, filtering, or saving is performed.

Parameters:

config (CellposeFlowConfig) – Configuration containing model parameters, image source, and inference settings. Only the following fields are used: - src_zarr: Source image array - model, model_dir: Model specification - batch_size, tile_overlap, flow3D_smooth, augment: Inference parameters - verbose: Logging control

Return type:

tuple[ndarray, ndarray]

Returns:

  • dP (np.ndarray) – Displacement field with shape (3, Z, Y, X) in float16.

  • cellprob (np.ndarray) – Cell probability logits with shape (Z, Y, X) in float16.

Notes

  • GPU memory is explicitly freed after inference

  • Arrays are returned in float16 for memory efficiency

  • This function does not modify any files or zarr stores

See also

postprocess_flows

For postprocessing raw flows

calculate_flows

For complete flow calculation including postprocessing

sphero_vem.segmentation.cellpose.core.postprocess_flows(config, dP, cellprob, save_root=None)[source]#

Postprocess raw cellpose flows and save to zarr.

This function applies optional filtering and decomposition steps to raw flows, then saves both raw (if requested) and processed flows to zarr. This function is intended for debugging and iterative development of postprocessing pipelines.

Parameters:
  • config (CellposeFlowConfig) – Configuration containing postprocessing parameters and save paths. Relevant fields: - out_path: Destination zarr store path - seg_target: Target label group name - spacing_dir: Spacing directory name - save_raw_flows: Whether to save unprocessed flows - median_filter_cellprob: Whether to apply median filter - median_filter_size: Median filter size - guided_filter_cellprob: Whether to apply guided filter - guided_filter_radius, guided_filter_eps: Guided filter parameters - decompose_flows: Whether to decompose flows via Helmholtz-Hodge - decompose_flows_pad_fraction: Padding for flow decomposition - zarr_chunks: Chunk size for zarr arrays - verbose: Logging control

  • dP (np.ndarray) – Raw displacement field with shape (3, Z, Y, X), or (2, Y, X) if 2D.

  • cellprob (np.ndarray) – Raw cell probability logits with shape (Z, Y, X), or (Y, X) if 2D.

  • save_root (zarr.Group | None, optional) – Pre-opened zarr group for saving. If None, opens config.out_path. This allows external control over zarr cleanup operations.

Return type:

tuple[ndarray, ndarray]

Returns:

  • dP_processed (np.ndarray) – Processed displacement field (after optional decomposition).

  • cellprob_processed (np.ndarray) – Processed cell probability (after optional filtering).

Notes

  • Does NOT perform zarr group cleanup (caller’s responsibility)

  • Suitable for iterative debugging of postprocessing parameters

  • GPU operations (decompose_flow) clean up their own memory

  • All arrays are saved as float16 for storage efficiency

See also

compute_raw_flows

For raw flow computation

calculate_flows

For complete flow calculation including zarr cleanup

sphero_vem.segmentation.cellpose.core.calculate_flows(config)[source]#

Segment volume stack using cellpose: compute flows and postprocess.

This is the main entry point for cellpose flow calculation. It performs model inference, postprocessing, and saving in a single call. For debugging or iterative development, use compute_raw_flows() and postprocess_flows() separately.

Parameters:

config (CellposeFlowConfig) – Complete configuration for flow calculation and postprocessing.

Return type:

None

Notes

  • Deletes existing labels/{seg_target} group to ensure clean state

  • Calls compute_raw_flows() followed by postprocess_flows()

  • Maintains backward compatibility with existing scripts

See also

compute_raw_flows

For inference-only workflow

postprocess_flows

For postprocessing pre-computed flows

calculate_masks

For generating masks from processed flows

class sphero_vem.segmentation.cellpose.core.CellposeMaskConfig(root_path, seg_target, spacing_dir='100-100-100', label_root=None, niter=200, cellprob_threshold=-0.5, flow_threshold=0.4, min_diam=3, expand_labels=False, max_expansion_steps=5, merge_masks=True, gaussian_edge_sigma=2.0, merge_weight_threshold=0.2, merge_contact_threshold=0.2, device='cuda', zarr_chunks=None)[source]#

Bases: BaseConfig

Configuration for generating segmentation masks from Cellpose flows.

Parameters:
  • root_path (Path) – Root directory of the Zarr archive.

  • seg_target (str) – Segmentation target name (e.g. "cells" or "nuclei").

  • spacing_dir (str, optional) – Spacing directory that identifies the flow arrays. Default is "100-100-100".

  • label_root (str | None, optional) – Optional prefix group path for non-standard label locations within the Zarr archive. Default is None.

  • niter (int, optional) – Number of Euler integration steps in the flow dynamics solver. Default is 200.

  • cellprob_threshold (float, optional) – Cellprob logit threshold; voxels below this value are excluded. Default is -0.5.

  • flow_threshold (float, optional) – Maximum allowed flow error for retaining a mask. Default is 0.4.

  • min_diam (float, optional) – Minimum object diameter in micrometers used to derive min_size in voxels. Default is 3.

  • expand_labels (bool, optional) – Expand labels into the foreground mask after mask generation. Default is False.

  • max_expansion_steps (int, optional) – Maximum dilation iterations for label expansion. Default is 5.

  • merge_masks (bool, optional) – Merge adjacent under-segmented labels via RAG-based merging. Default is True.

  • gaussian_edge_sigma (float, optional) – Gaussian sigma for edge map computation during merging. Default 2.0.

  • merge_weight_threshold (float, optional) – Maximum edge weight for a merge to be accepted. Default is 0.2.

  • merge_contact_threshold (float, optional) – Minimum relative contact area for a merge to be accepted. Default 0.2.

  • device (str, optional) – Torch device string for mask generation. Default is "cuda".

  • zarr_chunks (tuple[int] | None, optional) – Chunk shape for the output mask array. If None, inherits source chunks.

sphero_vem.segmentation.cellpose.core.calculate_masks(config)[source]#

Generate segmentation masks from pre-computed Cellpose flows.

Loads cellprob and dP arrays from the Zarr archive, runs the Cellpose dynamics solver, applies optional label expansion and RAG-based merging, and writes the final mask array back to the archive.

Parameters:

config (CellposeMaskConfig) – Configuration specifying flow sources, solver parameters, and post-processing options.

Return type:

None

This module contains functions used to finetune Cellpose models

class sphero_vem.segmentation.cellpose.finetuning.CellposeFinetuneConfig(dir_labeled, learning_rate=5e-05, batch_size=8, n_epochs=100, test_size=0.2, random_state=42, seg_target='cells', save_predictions=False, use_bfloat16=True)[source]#

Bases: BaseConfig

Configuration for fine-tuning a Cellpose-SAM model.

Parameters:
  • dir_labeled (Path | str) – Directory containing labeled training images and a manifest.json with "spacing" and "processing" keys.

  • learning_rate (float, optional) – Initial learning rate. Default is 5e-5.

  • batch_size (int, optional) – Training batch size. Default is 8.

  • n_epochs (int, optional) – Number of training epochs. Default is 100.

  • test_size (float, optional) – Fraction of labeled images reserved for testing. Default is 0.2.

  • random_state (int, optional) – Random seed for the train/test split. Default is 42.

  • seg_target (str, optional) – Segmentation target: "cells" or "nuclei". Default is "cells".

  • save_predictions (bool, optional) – Save model predictions on test images after training. Default is False.

  • use_bfloat16 (bool, optional) – Use bfloat16 mixed precision during training. Default is True.

class sphero_vem.segmentation.cellpose.finetuning.CellposeLogger(config)[source]#

Bases: object

Context manager for Cellpose training logging via Weights & Biases.

Initializes a WandB run, attaches a _CellposeLogHandler to the cellpose.train logger, and provides cleanup utilities.

Parameters:

config (CellposeFinetuneConfig) – Fine-tuning configuration used to initialize the WandB run.

stop()[source]#

Stop logging and cleanup

Return type:

None

save_losses(train_losses, test_losses)[source]#

Log detailed epoch-by-epoch data

Return type:

None

Parameters:
sphero_vem.segmentation.cellpose.finetuning.finetune_cellpose(config)[source]#

Finetune a Cellpose model using the parameters in the configuration.

This function handles the complete fine-tuning process for a Cellpose model, including data splitting and logging.

Parameters:

config (CellposeConfig) – Configuration object containing all necessary parameters for fine-tuning.

Various utility functions for Cellpose segmentation

sphero_vem.segmentation.cellpose.utils.region_fill(seeds, foreground, max_expansion_steps=10)[source]#

Expand integer seeds by iterative grey dilation, constrained to a foreground mask.

Each iteration expands labels by 1 voxel (6-connectivity). Background regions act as hard barriers since expansion is strictly limited to the foreground mask.

Parameters:
  • seeds (ArrayLike) – Integer label array (0 = background).

  • foreground (ArrayLike) – Boolean mask. Expansion is strictly limited to True voxels.

  • max_expansion_steps (int, optional) – Maximum dilation iterations. Default 50.

Returns:

Expanded label array, zero outside foreground.

Return type:

np.ndarray

sphero_vem.segmentation.cellpose.utils.upsample_masks(root_path, seg_target, target_spacing, src_spacing=(100, 100, 100), erosion_iterations=2, cellprob_threshold=0.0, store_chunks=None, label_root=None, n_workers=4)[source]#

Upsample low-resolution Cellpose labels to a higher-resolution target spacing.

Reads low-resolution masks and the corresponding high-resolution cellprob array from a Zarr archive, runs region-fill upsampling, and writes the result back to the archive under the target spacing path.

Parameters:
  • root_path (Path) – Path to the root Zarr archive.

  • seg_target (str) – Name of the segmentation target (e.g. "cells" or "nuclei").

  • target_spacing (tuple[int, float]) – Target voxel spacing (Z, Y, X) in nanometers.

  • src_spacing (tuple[int, int, int], optional) – Source (low-resolution) voxel spacing. Default is (100, 100, 100).

  • erosion_iterations (int, optional) – Number of erosion steps applied to seeds before zooming. Default is 2.

  • cellprob_threshold (float, optional) – Logit threshold for the foreground mask. Default is 0.0.

  • store_chunks (tuple[int] | None, optional) – Chunk shape for the output Zarr array. If None, inherits source chunks.

  • label_root (str | None, optional) – Optional prefix path for the label group within the archive. If None, labels are read from labels/{seg_target}/....

  • n_workers (int, optional) – Number of worker threads for Dask resampling. Default is 4.

Return type:

None

sphero_vem.segmentation.cellpose.utils.match_predictions(ground_truth, predictions)[source]#

Remap predicted label IDs to match ground-truth label IDs.

Uses Cellpose IoU matching to align predicted labels to ground-truth labels so that paired labels share the same integer ID.

Parameters:
  • ground_truth (numpy.ndarray) – Integer label array of ground-truth segmentations.

  • predictions (numpy.ndarray) – Integer label array of predicted segmentations.

Returns:

Relabeled prediction array where matched labels carry the same ID as the corresponding ground-truth label.

Return type:

numpy.ndarray

sphero_vem.segmentation.cellpose.utils.build_rag(labels, cellprob, edge_map)[source]#

Builds a RAG of cellpose labels using GPU acceleration when possible.

Parameters:
  • labels (np.ndarray) – Integer array containing the predicted labels

  • cellprob (np.ndarray) – Cellprob array containing the cell probability logits

  • edge_map (np.ndarray) – Edge map normalized to [0, 1]

Returns:

Region adjacency graph with the edge parameters - ‘prob_weight’: mean cell probability (probability of mean logit value) - ‘edge_weight’: mean edge probability - ‘count’: number of boundary voxels - ‘weight’: 1 - prob_weight + edge_weight

Return type:

graph.RAG

sphero_vem.segmentation.cellpose.utils.calc_surface_rag(rag)[source]#

Calculate an approximation of label area from a region adjacency graph (RAG).

Parameters:

rag (skimage.graph.RAG) – A region adjaceny graph. The RAG should include background nodes and use only face connectivity (connectivity=1). The function will use the “count” edge parameter to calculate the total surface of each label.

Returns:

A dictionary in the form {label_num: total_surface}

Return type:

dict[int, float]

sphero_vem.segmentation.cellpose.utils.gaussian_edge_map(image, sigma)[source]#

Calculate edge map of an image using Gaussian-smoothed gradient magnitude

The edge map is clipped to 1st and 99th percentile and normalized. The function automatically uses GPU acceleration when available.

Parameters:
  • image (ArrayLike) – The image to be analyzed.

  • sigma (float | int) – The standard deviation of the Gaussian filter applied before gradient calculation.

Returns:

The edge map of the image, normalized to [0, 1].

Return type:

ArrayLike

sphero_vem.segmentation.cellpose.utils.rag_to_df(rag)[source]#

Convert a RAG to a tidy DataFrame for inspection and debugging.

Flattens the edge data of a RAG (as produced by build_rag) into a DataFrame where each row corresponds to one edge between two adjacent label regions.

Parameters:

rag (graph.RAG) – Region adjacency graph, as returned by build_rag.

Returns:

One row per edge with columns:

  • u, v : int — the two adjacent label IDs.

  • weight : float — merge cost (1 - prob_weight + edge_weight).

  • prob_weight : float — mean cell probability across boundary voxels (sigmoid of mean logit).

  • edge_weight : float — mean edge map value across boundary voxels.

  • count : int — number of boundary voxels between the two regions.

Return type:

pd.DataFrame

See also

build_rag

Constructs the RAG from Cellpose labels, cellprob logits, and an edge map.

Evaluation of Cellpose segmentation accuracy

sphero_vem.segmentation.cellpose.evaluation.calculate_ap(ground_truth, predictions, threshold_step=0.05)[source]#

Calculate average precision and related metrics at different IoU thresholds.

This function evaluates segmentation predictions against ground truth by computing the average precision, as well as counting the number of true positives, false positives, and false negatives at different Jaccard index (IoU) thresholds.

Parameters:
  • ground_truth (np.ndarray) – Ground truth segmentation mask with instance labels. Each object should have a unique integer ID > 0.

  • predictions (np.ndarray) – Predicted segmentation mask with instance labels. Each predicted object should have a unique integer ID > 0.

  • threshold_step (float, optional) – Step size for IoU thresholds, defaults to 0.05. Thresholds will be generated as [threshold_step, 2*threshold_step, …, < 1.0]

Returns:

DataFrame containing evaluation metrics with columns: - ‘iou_thresholds’: IoU threshold values - ‘average_precision’: AP score at each threshold - ‘true_positives’: Number of true positive detections - ‘false_positives’: Number of false positive detections - ‘false_negatives’: Number of false negative detections

Return type:

pd.DataFrame

sphero_vem.segmentation.cellpose.evaluation.evaluate_segmentation(root_path, gt_root_path, array_path, out_dir=None, seg_target=None)[source]#

Calculate accuracy for a volume segmentation with several metrics and saves them.

Parameters:
  • root_path (Path) – The path the the zarr root store.

  • gt_root_path (Path) – The path the root of the labeled dataset. It should have subdirectories with structure gt_root_path/spacing_dir/labels. spacing_dir should is the last element of array_path.

  • array_path (str) – Path to the mask array to analyse relative to root_path.

  • out_dir (Path | None, optional) – Optional destination path for the calculated metrics. Id specified, metrics will be saved as out_dir/segmentation-eval.parquet, otherwise they will be saved as tables/segmentation-eval.parquet within the parent group of the mask array. Default is None.

  • seg_target (str | None) – If this is specified, accuracy metrics will be calculated against ground truths for this segmentation target, regardless of the actual target they were calculated on. If None, segmentation target will be read from the mask array. This is useful when comparing cross-class detections, or when evaluating pretrained models, which were not trained on a specific custom target. Default is None.

Returns:

A dataframe with the calculated metrics.

Return type:

pd.DataFrame

Nanoparticles#

Nanoparticle segmentation

class sphero_vem.segmentation.np.core.NanoparticleSegConfig(root_path, spacing_dir, verbose=False, max_iter=10000, eps=1e-12, nll_tol=1e-10, sampling_step=1, percent_th_low=99.5, percent_th_high=99.8, halo_pad=20, min_size=20, posterior_th=0.95, beta_params=(1.0, 20.0), zarr_chunks=(1, 1024, 1024), model_name=None)[source]#

Bases: BaseConfig

Configuration for nanoparticle (NP) segmentation via empirical Bayes EM.

Parameters:
  • root_path (Path) – Path to the root zarr store containing the image stack.

  • spacing_dir (str) – Array path within images/ (e.g. "50-10-10").

  • verbose (bool, optional) – Enable progress bars and diagnostic output. Default is False.

  • max_iter (int, optional) – Maximum number of EM iterations. Default is 10000.

  • eps (float, optional) – Numerical floor added to PMFs to prevent log(0). Default is 1e-12.

  • nll_tol (float, optional) – Convergence tolerance: stops when the per-iteration decrease in NLL falls below this value. Default is 1e-10.

  • sampling_step (int, optional) – Slice stride used when sampling the stack for histogram estimation; 1 uses every slice. Default is 1.

  • percent_th_low (float, optional) – Lower intensity threshold as a CDF percentile of the stack histogram. Pixels above this percentile are treated as NP candidates. Default is 99.5.

  • percent_th_high (float, optional) – Upper intensity threshold as a CDF percentile; pixels above this are always excluded from the background histogram. Default is 99.8.

  • halo_pad (int, optional) – Padding in pixels added around detected NP seeds when building the background histogram. Default is 20.

  • min_size (int, optional) – Minimum connected-component size in pixels for NP seed detection during background extraction. Default is 20.

  • posterior_th (float, optional) – Posterior probability threshold for binarization, used externally by label_nanoparticles. Default is 0.95.

  • beta_params (tuple[float, float], optional) – Shape parameters (alpha, beta) of the Beta prior on the per-image NP mixing weight pi. Default is (1.0, 20.0).

  • zarr_chunks (tuple[int, int, int], optional) – Chunk shape (Z, Y, X) for the posterior zarr array. Default is (1, 1024, 1024).

  • model_name (str | None) – Name of the fitted model. If None, the model name will be assigned automatically as f"nps-{timestamp()}".

class sphero_vem.segmentation.np.core.NanoparticleSegmentation(config)[source]#

Bases: object

Two-component intensity mixture model for nanoparticle segmentation.

Decomposes the voxel intensity histogram of an SBF-SEM stack into a background distribution and a nanoparticle (NP) distribution using an Expectation-Maximization algorithm. Per-slice posterior probabilities are estimated by MAP optimization of a per-image mixing weight.

Parameters:

config (NanoparticleSegConfig) – Segmentation configuration.

config#

Configuration passed at construction.

Type:

NanoparticleSegConfig

stack_root#

Open zarr group at config.stack_root.

Type:

zarr.Group

volume_stack#

Image array at images/{config.spacing_dir} within the group.

Type:

zarr.Array

p_stack#

Full-stack intensity PMF of shape (256,). Set by fit().

Type:

numpy.ndarray

p_bg#

Background intensity PMF of shape (256,). Set by fit().

Type:

numpy.ndarray

p_np#

Fitted NP intensity PMF of shape (256,). Set by fit().

Type:

numpy.ndarray

hist_stack#

Raw intensity histogram of the stack, shape (256,). Set by fit().

Type:

numpy.ndarray

hist_bg#

Raw background pixel histogram, shape (256,). Set by fit().

Type:

numpy.ndarray

summary_fit#

EM convergence summary with keys w_bg (final background mixing weight), nll (final negative log-likelihood), and nit (number of iterations). Set by fit().

Type:

dict

Notes

Call fit() before predict(). A fitted model can be persisted with save() and restored from disk with load().

classmethod load(model_dir)[source]#

Load a pretrained model from a directory. The directory is expected to have a training_manifest.json and model_params.npz of the correct format

Return type:

Self

Parameters:

model_dir (str | Path)

save(target_dir)[source]#

Save the calculated probabilities and the training parameters in the specified directory as model_params.npz and training_manifest.json, respectively. It also saves the summary of the fit results in fit_results.json

Return type:

None

Parameters:

target_dir (str | Path)

fit()[source]#

Fit the two-component mixture model to the image stack.

Computes the full-stack intensity histogram (p_stack), extracts the background histogram (p_bg), and runs EM to estimate the NP intensity distribution (p_np). Populates hist_stack, hist_bg, p_stack, p_bg, p_np, and summary_fit. Must be called before predict().

Return type:

None

predict()[source]#

Compute and save the per-voxel NP posterior probability map.

For each slice, estimates the per-image NP mixing weight pi by MAP optimization, then computes the per-pixel posterior probability under the fitted mixture. Results are written to labels/nps/posterior/{spacing_dir} in the zarr store as a float16 array.

Return type:

None

Notes

Requires a fitted model; call fit() or load() first.

sphero_vem.segmentation.np.core.label_nanoparticles(root_path, spacing, threshold, radius=1, connectivity=2, min_size=10)[source]#

Threshold posterior >= threshold and label nanoparticle binary masks.

Masks are first subject to a binary closing with given radius. Then, labeling is done with the specified connectivity and labels smaller than min_size (in voxels) are discarded. The volume is finally relabeled to have sequential label IDs.

Parameters:
  • root_path (Path) – Path to the root of the zarr store

  • spacing (tuple[int, int, int]) – Spacing to use for the labeling

  • threshold (float) – Theshold to apply to the nanoparticle posterior, such that posterior >= threshold. It should be between 0 and 1.

  • radius (int) – Radius in voxels for a ball element using during binary closing. Default is 1.

  • connectivity (int) – Connectivity used during labeling. Default is 2.

  • min_size (int) – Minimimum label size in voxels. Labels with size < min_size will be discarded. Default is 10.

Return type:

None

Notes

The posterior array is loaded fully into memory. For large volumes, ensure sufficient RAM is available before calling this function.

Utility functions used for nanoparticle segmentation

sphero_vem.segmentation.np.utils.bincount_ubyte(image)[source]#

Compute a 256-bin intensity histogram for a uint8 image.

This function uses GPU acceleration when available.

Parameters:

image (ArrayLike) – Input uint8 image array of any shape.

Returns:

Integer histogram of shape (256,) with bin counts per intensity level.

Return type:

numpy.ndarray

sphero_vem.segmentation.np.utils.downsample_posterior(root_path, sigma, dst_spacing, src_spacing=(50, 10, 10), n_workers=4)[source]#

Downsample posterior probabilities via logit-space Gaussian smoothing and average pooling.

Parameters:
  • root_path (Path) – Path to the Zarr archive.

  • sigma (tuple[float, float, float]) – Gaussian smoothing sigma (Z, Y, X) applied in logit space.

  • dst_spacing (tuple[int, int, int]) – Target voxel spacing (Z, Y, X) in nanometers.

  • src_spacing (tuple[int, int, int]) – Source voxel spacing (Z, Y, X) in nanometers. Default (50, 10, 10).

  • n_workers (int) – Number of threads for dask threaded scheduler. Default 4.

Return type:

None