Python how to get a list of color that used in one image
I have used something like the following a few times to analyze graphs:
>>> from PIL import Image
>>> im = Image.open('polar-bear-cub.jpg')
>>> from collections import defaultdict
>>> by_color = defaultdict(int)
>>> for pixel in im.getdata():
... by_color[pixel] += 1
>>> by_color
defaultdict(<type 'int'>, {(11, 24, 41): 8, (53, 52, 58): 8, (142, 147, 117): 1, (121, 111, 119): 1, (234, 228, 216): 4
Ie, there are 8 pixels with rbg value (11, 24, 41), and so on.
The getcolors method should do the trick. See the docs.
Edit: That link is broken. Pillow seems to be the go-to lib now, forked from PIL. New Docs
Image.open('file.jpg').getcolors() => a list of (count, color) tuples or None
I'd like to add that the .getcolors() function only works if the image is in an RGB mode of some sort.
I had this problem where it would return a list of tuples with (count, color) where color was just a number. Took me a while to find it, but this fixed it.
from PIL import Image
img = Image.open('image.png')
colors = img.convert('RGB').getcolors() #this converts the mode to RGB