Skip to content

tissue_components

tissue_components

tissue_components(
    img: ndarray,
    label: ndarray | None = None,
    device: str = "cpu",
) -> tuple[np.ndarray, np.ndarray]

Segment background and dark-component masks using RGB color clusters.

Parameters:

Name Type Description Default
img ndarray

RGB H&E image with shape (H, W, 3) and pixel values in [0, 255].

required
label ndarray | None

Optional nuclei labels with shape (H, W); positive labels are included in the dark-component mask.

None
device str

"cpu" or "cuda". CUDA clustering requires CuPy/cuML; mask cleanup checks its own CUDA dependencies.

'cpu'

Returns:

Type Description
tuple[ndarray, ndarray]

Background and dark-component NumPy boolean masks with shape (H, W).

Raises:

Type Description
RuntimeError

If a required CUDA backend is unavailable.

ValueError

If clustering rejects the inputs or device.

Source code in src/histolytics/utils/im.py
def tissue_components(
    img: np.ndarray, label: np.ndarray | None = None, device: str = "cpu"
) -> tuple[np.ndarray, np.ndarray]:
    """Segment background and dark-component masks using RGB color clusters.

    Args:
        img: RGB H&E image with shape (H, W, 3) and pixel values in [0, 255].
        label: Optional nuclei labels with shape (H, W); positive labels are
            included in the dark-component mask.
        device: "cpu" or "cuda". CUDA clustering requires CuPy/cuML; mask cleanup
            checks its own CUDA dependencies.

    Returns:
        Background and dark-component NumPy boolean masks with shape (H, W).

    Raises:
        RuntimeError: If a required CUDA backend is unavailable.
        ValueError: If clustering rejects the inputs or device.
    """
    # mask out dark pixels
    kmasks = kmeans_img(img, n_clust=3, device=device)

    if not np.any(kmasks):
        bg_mask = np.zeros(kmasks.shape[:2], dtype=bool)
        dark_mask = np.zeros(kmasks.shape[:2], dtype=bool)
        return bg_mask, dark_mask

    if device == "cuda":
        bg_mask, dark_mask = _get_tissue_bg_fg_cp(img, kmasks, label)
    else:
        bg_mask, dark_mask = _get_tissue_bg_fg_np(img, kmasks, label)

    bg_mask = rm_objects_mask(
        erosion(bg_mask, footprint_rectangle((3, 3))), min_size=1000, device=device
    )
    dark_mask = rm_objects_mask(
        dilation(dark_mask, footprint_rectangle((3, 3))), min_size=200, device=device
    )

    # couldn't get this work with cupyx.ndimage..
    bg_mask = ndimage.binary_fill_holes(bg_mask)
    dark_mask = ndimage.binary_fill_holes(dark_mask)

    return bg_mask, dark_mask