Skip to content
Search

K-means clustering

lastmod 2024-03-27created 2022-07-128 edits

The k-means algorithm groups given data into k clusters and works by minimizing the variance of the distance to each cluster. It is a form of unsupervised learning and serves to assign labels to unlabeled input data.

Color Quantization example

Color quantization is the process of reducing the number of colors used in an image. One purpose of this processing is to reduce memory usage. Let's use K-Means clustering for color quantization.

There is nothing new added here. There are 3 features: R, G, and B. The image's pixel data is made into an Mx3 array, where M is the number of pixels in the image. After clustering, each pixel's value is replaced with the value of the centroid (also R, G, B) of the cluster it belongs to. Then the Mx3 array is reshaped back to the original image size. The code is as follows.

import numpy as np
import cv2

img = cv2.imread('./data/harleyQuinnA.jpg')
Z = img.reshape((-1,3))

# convert to np.float32
Z = np.float32(Z)

# define criteria, number of clusters(K) and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 7
ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)

# Now convert back into uint8, and make original image
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((img.shape))

cv2.imshow('res2',res2)
cv2.waitKey(0)
cv2.destroyAllWindows()

K-mean_-color_quantization-_sample.png

See also

Favorite site

author Zer0 sitemap