user469652
user469652

Reputation: 51211

Python how to get a list of color that used in one image

Python how to get a list of color that used in one 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?

Upvotes: 20

Views: 51657

Answers (5)

Mikhail Gerasimov
Mikhail Gerasimov

Reputation: 39516

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

Upvotes: 2

Jake
Jake

Reputation: 13141

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

Upvotes: 33

Eyal Enav
Eyal Enav

Reputation: 81

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)

Upvotes: 7

Wouter Mol
Wouter Mol

Reputation: 129

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

Upvotes: 12

unmounted
unmounted

Reputation: 34388

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.

Upvotes: 13

Related Questions