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
2009-06-30 21:59:51
+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 ?
ΤΖΩΤΖΙΟΥ
2009-07-01 20:38:53
+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
2009-07-02 14:22:06