Skip to content

sopa.segmentation.methods

sopa.segmentation.methods.cellpose_patch(diameter, channels, model_type='cyto3', pretrained_model=False, cellpose_model_kwargs=None, **cellpose_eval_kwargs)

Creation of a callable that runs Cellpose segmentation on a patch

Parameters:

Name Type Description Default
diameter float

Cellpose diameter parameter

required
channels list[str]

List of channel names

required
model_type str

Cellpose model type

'cyto3'
pretrained_model str | bool

Path to the pretrained model to be loaded

False
cellpose_model_kwargs dict | None

Kwargs to be provided to the cellpose.models.CellposeModel object

None
**cellpose_eval_kwargs int

Kwargs to be provided to model.eval (where model is a cellpose.models.CellposeModel object)

{}

Returns:

Type Description
Callable

A callable whose input is an image of shape (C, Y, X) and output is a cell mask of shape (Y, X). Each mask value >0 represent a unique cell ID

Source code in sopa/segmentation/methods.py
def cellpose_patch(
    diameter: float,
    channels: list[str],
    model_type: str = "cyto3",
    pretrained_model: str | bool = False,
    cellpose_model_kwargs: dict | None = None,
    **cellpose_eval_kwargs: int,
) -> Callable:
    """Creation of a callable that runs Cellpose segmentation on a patch

    Args:
        diameter: Cellpose diameter parameter
        channels: List of channel names
        model_type: Cellpose model type
        pretrained_model: Path to the pretrained model to be loaded
        cellpose_model_kwargs: Kwargs to be provided to the `cellpose.models.CellposeModel` object
        **cellpose_eval_kwargs: Kwargs to be provided to `model.eval` (where `model` is a `cellpose.models.CellposeModel` object)

    Returns:
        A `callable` whose input is an image of shape `(C, Y, X)` and output is a cell mask of shape `(Y, X)`. Each mask value `>0` represent a unique cell ID
    """
    try:
        from cellpose import models
    except ImportError:
        raise ImportError(
            "To use cellpose, you need its corresponding sopa extra: `pip install 'sopa[cellpose]'` (normal mode) or `pip install -e '.[cellpose]'` (if using snakemake)"
        )

    cellpose_model_kwargs = cellpose_model_kwargs or {}

    model = models.CellposeModel(
        model_type=model_type, pretrained_model=pretrained_model, **cellpose_model_kwargs
    )

    if isinstance(channels, str) or len(channels) == 1:
        channels = [0, 0]  # gray scale
    elif len(channels) == 2:
        channels = [1, 2]
    else:
        raise ValueError(f"Provide 1 or 2 channels. Found {len(channels)}")

    def _(patch: np.ndarray):
        mask, *_ = model.eval(patch, diameter=diameter, channels=channels, **cellpose_eval_kwargs)
        return mask

    return _