Skip to content

kmeans_img

kmeans_img

kmeans_img(
    img: ndarray,
    n_clust: int = 3,
    seed: int = 42,
    device: str = "cpu",
) -> np.ndarray

Cluster image pixels by RGB color using the requested backend.

Parameters:

Name Type Description Default
img ndarray

RGB image with shape (H, W, 3).

required
n_clust int

Number of color clusters.

3
seed int

Random seed passed to the selected KMeans implementation.

42
device str

"cpu" for scikit-learn or "cuda" for CuPy/cuML. CUDA clustering does not require cuCIM.

'cpu'

Returns:

Type Description
ndarray

NumPy integer label image with shape (H, W), with labels starting at 1.

ndarray

Images with fewer unique colors than requested clusters return zeros.

Raises:

Type Description
RuntimeError

If CUDA clustering is requested without CuPy/cuML.

ValueError

If the device is unsupported or KMeans rejects its inputs.

Source code in src/histolytics/utils/im.py
def kmeans_img(
    img: np.ndarray, n_clust: int = 3, seed: int = 42, device: str = "cpu"
) -> np.ndarray:
    """Cluster image pixels by RGB color using the requested backend.

    Args:
        img: RGB image with shape (H, W, 3).
        n_clust: Number of color clusters.
        seed: Random seed passed to the selected KMeans implementation.
        device: "cpu" for scikit-learn or "cuda" for CuPy/cuML. CUDA clustering
            does not require cuCIM.

    Returns:
        NumPy integer label image with shape (H, W), with labels starting at 1.
        Images with fewer unique colors than requested clusters return zeros.

    Raises:
        RuntimeError: If CUDA clustering is requested without CuPy/cuML.
        ValueError: If the device is unsupported or KMeans rejects its inputs.
    """
    if device == "cuda" and not _has_cuml:
        raise RuntimeError(
            "CuPy and cuML are required for GPU acceleration (device='cuda'). "
            "Please install them with:\n"
            "  pip install cupy-cuda12x cuml-cu12\n"
            "or set device='cpu'."
        )

    # Check for sufficient color variation
    pixels = img.reshape(-1, 3)
    unique_colors = np.unique(pixels, axis=0)

    # If we have fewer unique colors than requested clusters, reduce n_clust
    if len(unique_colors) < n_clust:
        n_clust = max(1, len(unique_colors))
        return np.zeros((img.shape[0], img.shape[1]), dtype=np.int32)

    if device == "cuda":
        return _kmeans_cp(img, n_clust=n_clust, seed=seed)
    elif device == "cpu":
        return _kmeans_np(img, n_clust=n_clust, seed=seed)
    else:
        raise ValueError(f"Invalid device '{device}'. Use 'cpu' or 'cuda'.")