Shortcuts

slideflow.cellseg

This module contains utility functions for performing whole-slide image cell segmentation with Cellpose.

See Cell Segmentation for more information.

segment_slide(slide: WSI | str, model: cellpose.models.Cellpose | str = 'cyto2', *, diam_um: float | None = None, diam_mean: int | None = None, window_size: int | None = None, downscale: float | None = None, batch_size: int = 8, gpus: int | Iterable[int] | None = (0,), spawn_workers: bool = True, pb: Progress | None = None, pb_tasks: List[TaskID] | None = None, show_progress: bool = True, save_flow: bool = True, cp_thresh: float = 0.0, flow_threshold: float = 0.4, interp: bool = True, tile: bool = True, verbose: bool = True, device: str | None = None) Segmentation[source]

Segment cells in a whole-slide image, returning masks and centroids.

Parameters:

slide (str, slideflow.WSI) – Whole-slide image. May be a path (str) or WSI object (slideflow.WSI).

Keyword Arguments:
  • model (str, cellpose.models.Cellpose) – Cellpose model to use for cell segmentation. May be any valid cellpose model. Defaults to ‘cyto2’.

  • diam_um (float, optional) – Cell diameter to detect, in microns. Determines tile extraction microns-per-pixel resolution to match the given pixel diameter specified by diam_mean. Not used if slide is a sf.WSI object.

  • diam_mean (int, optional) – Cell diameter to detect, in pixels (without image resizing). If None, uses Cellpose defaults (17 for the ‘nuclei’ model, 30 for all others).

  • window_size (int) – Window size, in pixels, at which to segment cells. Not used if slide is a sf.WSI object.

  • downscale (float) – Factor by which to downscale generated masks after calculation. Defaults to None (keep masks at original size).

  • batch_size (int) – Batch size for cell segmentation. Defaults to 8.

  • gpus (int, list(int)) – GPUs to use for cell segmentation. Defaults to 0 (first GPU).

  • spawn_workers (bool) – Enable spawn-based multiprocessing. Increases cell segmentation speed at the cost of higher memory utilization.

  • pb (rich.progress.Progress, optional) – Progress bar instance. Used for external progress bar tracking. Defaults to None.

  • pb_tasks (list(rich.progress.TaskID)) – Progress bar tasks. Used for external progress bar tracking. Defaults to None.

  • show_progress (bool) – Show a tqdm progress bar. Defaults to True.

  • save_flow (bool) – Save flow values for the whole-slide image. Increases memory utilization. Defaults to True.

  • cp_thresh (float) – Cell probability threshold. All pixels with value above threshold kept for masks, decrease to find more and larger masks. Defaults to 0.

  • flow_threshold (float) – Flow error threshold (all cells with errors below threshold are kept). Defaults to 0.4.

  • interp (bool) – Interpolate during 2D dynamics. Defaults to True.

  • tile (bool) – Tiles image to decrease GPU/CPU memory usage. Defaults to True.

  • verbose (bool) – Verbose log output at the INFO level. Defaults to True.

Returns:

slideflow.cellseg.Segmentation

Segmentation

class Segmentation(masks: ndarray, *, slide: WSI | None = None, flows: ndarray | None = None, styles: ndarray | None = None, diams: ndarray | None = None, wsi_dim: Tuple[int, int] | None = None, wsi_offset: Tuple[int, int] | None = None)[source]

Organizes a collection of cell segmentation masks for a slide.

Parameters:

masks (np.ndarray) – Array of masks, dtype int32, where 0 represents non-segmented background, and each segmented mask is represented by unique increasing integers.

Keyword Arguments:
  • slide (slideflow.WSI) – If provided, Segmentation can coordinate extracting tiles at mask centroids. Defaults to None.

  • flows (np.ndarray) – Array of flows, dtype float32. Defaults to None.

  • wsi_dim (tuple(int, int)) – Size of masks in the slide pixel space (highest magnification). Used to align the mask array to a corresponding slide. Required for calculating centroids. Defaults to None.

  • wsi_offset (tuple(int, int)) – Top-left starting location for masks, in slide pixel space (highest magnification). Used to align the mask array to a corresponding slide. Required for calculating centroids. Defaults to None.

  • styles (np.ndarray) – Array of styles, currently ignored.

  • diams (np.ndarray) – Array of diameters, currently ignored.

apply_rois(self, scale: float, annpolys: List[shapely.geometry.Polygon]) None

Apply regions of interest (ROIs), excluding masks outside ROIs.

Parameters:
  • scale (float) – ROI scale (roi size / WSI base dimension size).

  • annpolys (list(shapely.geometry.Polygon)) – List of ROI polygons, as available in slideflow.WSI.roi_polys.

calculate_centroids(self, force: bool = False) None

Calculate centroids.

Centroid values are buffered into Segmentation._centroids to reduce unnecessary recalculations.

Parameters:

force (bool) – Recalculate centroids, even if calculated before.

calculate_outlines(self, force: bool = False) None

Calculate mask outlines.

Mask outlines are buffered into Segmentation._outlines to reduce unnecessary recalculations.

Parameters:

force (bool) – Recalculate outlines, even if calculated before.

centroids(self, wsi_dim: bool = False) ndarray

Calculate and return mask centroids.

Parameters:

wsi_dim (bool) – Convert centroids from mask space to WSI space. Requires that wsi_dim was provided during initialization.

Returns:

A np.ndarray with shape (2, num_masks).

centroid_to_image(self, color: str = 'green') ndarray

Render an image with the location of all centroids as a point.

Parameters:

color (str) – Centroid color. Defaults to ‘green’.

extract_centroids(self, slide: str, tile_px: int = 128) Callable

Return a generator which extracts tiles from a slide at mask centroids.

Parameters:
  • slide (str) – Path to a slide.

  • tile_px (int) – Height/width of tile to extract at centroids. Defaults to 128.

Returns:

A generator which yields a numpy array, with shape

(tile_px, tile_px, 3), at each mask centroid.

mask_to_image(self, centroid=False, color='cyan', centroid_color='green')

Render an image of all masks.

Masks are rendered on a black background.

Parameters:
  • centroid (bool) – Include centroids as points on the image. Defaults to False.

  • color (str) – Color of the masks. Defaults to ‘cyan’.

  • centroid_color (str) – Color of centroid points. Defaults to ‘green’.

Returns:

np.ndarray

outline_to_image(self, centroid=False, color='red', centroid_color='green')

Render an image with the outlines of all masks.

Parameters:
  • centroid (bool) – Include centroids as points on the image. Defaults to False.

  • color (str) – Color of the mask outlines. Defaults to ‘red’.

  • centroid_color (str) – Color of centroid points. Defaults to ‘green’.

Returns:

np.ndarray

save(self, filename: str, centroids: bool = True, flows: bool = True) None

Save segmentation masks and metadata to *.zip.

A slideflow.cellseg.Segmentation object can be loaded from this file with .load().

Parameters:
  • filename (str) – Destination filename (ends with *.zip)

  • centroids (bool) – Save centroid locations.

  • flows (bool) – Save flows.