views:

688

answers:

4

I'm not sure how I would go about reducing the color palette of a PIL Image. I would like to reduce an image's palette to the 5 prominent colors found in that image. My overall goal is to do some basic color sampling.

A: 

I don't use PIL, but it seems pretty straightforward. Once you have an image you can do something along the lines of (pseudocode-ish):

image = Image.open("some_path_here.ext")
data = image.getdata()

for pixel in data:
  # not sure what's in a pixel, but it's suppose to be a "value"
  # So it's probably something resembling a 32-bit integer
  # Plus, you probably don't care, just stick these into a dict
  # and keep incrementing the count for each

Of course, if you want to get colors that are just "close", you might want to "transform" each pixel first through a filter to group "near" colors with each other.

Nick Bastin
A: 

I assume you want to do something more sophisticated than posterize. "Sampling" as you say, will take some finesse, as the 5 most common colors in the image are likely to be similar to one another. Maybe take a look at the 5 most separated peaks in a histogram.

bpowah
+1  A: 

The short answer is to use the Image.quantize method. For more info, see: How do I convert any image to a 4-color paletted image using the Python Imaging Library ?

ΤΖΩΤΖΙΟΥ
+4  A: 

That's easy, just use the undocumented colors argument:

result = image.convert('P', palette=Image.ADAPTIVE, colors=5)

I'm using Image.ADAPTIVE to avoid dithering

Nadia Alramli