23

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.

3 Answers3

36

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
  • 105,894
  • 35
  • 170
  • 151
  • Thank you, that's wonderful. I've always hated the PIL documentation. How do you then convert it back? With `image.convert("RGB", palette=Image.ADAPTIVE, colors=5)` or something else? – Cosine Jan 12 '14 at 18:10
  • 1
    This is now documented under [im.quantize](http://effbot.org/imagingbook/image.htm). – unutbu Feb 06 '14 at 21:47
  • 3
    @unutbu, `im.quantize` is deprecated. – c0dehunter Oct 28 '15 at 11:07
5

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.

Jonathan Root
  • 534
  • 2
  • 12
  • 30
Paul
  • 39,902
  • 14
  • 102
  • 121
3

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 ?

Community
  • 1
  • 1
tzot
  • 87,612
  • 28
  • 135
  • 198