main color detection in Python
Question: I have about 3000 images and 13 different colors (the background of the
majority of these images is white). If the main color of an image is one of
those 13 different colors, I'd like them to be associated.

I've seen similar questions like [Image color detection using
python](http://stackoverflow.com/questions/2270874/image-color-detection-
using-python) that ask for an average color algorithm. I've pretty much copied
that code, using the Python Image Library and histograms, and gotten it to
work - but I find that it's not too reliable for determining main colors.

Any ideas? Or libraries that could address this?

Thanks in advance!

:EDIT: Thanks guys - you all pretty much said the same thing, to create
"buckets" and increase the bucket count with each nearest pixel of the image.
I seem to be getting a lot of images returning "White" or "Beige," which is
also the background on most of these images. Is there a way to work around or
ignore the background?

Thanks again.


Answer: You can use the [getcolors](http://effbot.org/tag/PIL.Image.Image.getcolors)
function to get a list of all colors in the image. It returns a list of tuples
in the form:

    
    
    (N, COLOR)
    

where `N` is the number of times the color `COLOR` occurs in the image. To get
the maximum occurring color, you can pass the list to the
[max](http://docs.python.org/library/functions.html#max) function:

    
    
    >>> from PIL import Image
    >>> im = Image.open("test.jpg")
    >>> max(im.getcolors(im.size[0]*im.size[1]))
    (183, (255, 79, 79))
    

Note that I passed `im.size[0]*im.size[1]` to the getcolors function because
that is the maximum `maxcolors` value (see [the
docs](http://effbot.org/tag/PIL.Image.Image.getcolors) for details).

