A collection of sloppy snippets for scientific computing and data visualization in Python.

Sunday, July 8, 2012

Color quantization

The aim of color clustering is to produce a small set of representative colors which captures the color properties of an image. Using the small set of color found by the clustering, a quantization process can be applied to the image to find a new version of the image that has been "simplified," both in colors and shapes.
In this post we will see how to use the K-Means algorithm to perform color clustering and how to apply the quantization.
Let's see the code:

We have the original image on the top and the quantized version on the bottom. We can see that the image on the bottom has only six colors.
Now, we can plot the colors found with the clustering in the RGB space with the following code:

I was able to make the script work, but I have two issues:1) The input image is shown upside down.2) I would like to tell Python to save the quantization result to a specified location on the hard drive.

I finally figured out what was the problem. The output from the clustered variable is not properly an image, but something similar to an array (I guess). So I needed to convert that variable into an actual image before being able to save it. I did so with:output = Image.fromarray(clustered)

I don't know if it makes perfect sense, but in the end I'm now able to achieve what I was looking for :)Thank you for the script and for the help.