Image.kmeans_color#

Image.kmeans_color(k: int | None = None, centroids: ndarray | None = None, seed: int | None = None) tuple[Self, ndarray, float] | Self[source]#

k-means color clustering

Training

param k:

number of clusters, defaults to None

type k:

int, optional

param seed:

random number seed, defaults to None

type seed:

int, optional

return:

label image, centroids and residual

rtype:

Image, ndarray(P,k), float

The pixels are grouped into k clusters based on their Euclidean distance from k cluster centroids. Clustering is iterative and the initial cluster centroids are random.

The method returns a label image, indicating the assigned cluster for each input pixel, the cluster centroids and a residual.

Example:

>>> from machinevisiontoolbox import Image
>>> targets = Image.Read("tomato_124.png", dtype="float", gamma="sRGB")
>>> ab = targets.colorspace("L*a*b*").plane("a*:b*")
>>> targets_labels, targets_centroids, resid = ab.kmeans_color(k=3, seed=0)
>>> targets_centroids
array([[-19.4555,  -1.3746,  39.8559],
       [ 31.0359,   2.6728,  24.0851]], dtype=float32)

Classification

param centroids:

cluster centroids from training phase

type centroids:

ndarray(P,k)

return:

label image

rtype:

Image

Pixels in the input image are assigned the label of the closest centroid.

Note

The colorspace of the images could a chromaticity space to classify objects while ignoring brightness variation.

references:

Important

Uses OpenCV function cv2.kmeans which accepts multiple-channel, CV_32F images (images are automatically converted to float32).

Seealso:

opencv.kmeans