Reducing the color palette using k-means

Now let's reduce these 16 million colors to just 16 colors by telling k-means to cluster all color variations into 16 distinct clusters. We use the before mentioned procedure, but now specify 16 as the number of clusters:

In [9]: criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER,...                 10, 1.0)...     flags = cv2.KMEANS_RANDOM_CENTERS...     img_data = img_data.astype(np.float32)...     compactness, labels, centers = cv2.kmeans(img_data,...                                               16, None, criteria,...                                               10, flags)

The resulting cluster corresponds to the 16 colors of our reduced color palette. Visual inspection of the centers array reveals that all colors have three entries--B, G, and R--with values between 0 and 1:

In [10]: centersOut[10]: ...

Get Machine Learning for OpenCV now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.