Python how to get a list of color that used in one image
Python how to get a list of color that used in on开发者_如何学JAVAe image
I use PIL, and I want to have a dictionary of colors that are used in this image, including color(key) and number of pixel points it used.
How to do that?
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 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.
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
See https://github.com/fengsp/color-thief-py "Grabs the dominant color or a representative color palette from an image. Uses Python and Pillow"
from colorthief import ColorThief
color_thief = ColorThief('/path/to/imagefile')
# get the dominant color
dominant_color = color_thief.get_color(quality=1)
# build a color palette
palette = color_thief.get_palette(color_count=6)
getcolors()
returns None
if number of colors in the image is greater than maxcolor
argument. The function also works only with 'RGB' images. It's not very convenient.
getdata()
on the other hand can be utilized in very convenient way together with Counter:
from collections import Counter
colors = Counter(image.getdata()) # dict: color -> number
set(colors) # set of unique colors
len(colors) # number of unique colors
colors[(0, 0, 0)] # black color frequency
max(colors, key=colors.get) # most frequent color
精彩评论