O'Reilly logo

Machine Learning for OpenCV by Michael Beyeler

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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]: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required