Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 840
user469652 Avatar asked Jan 10 '11 05:01

user469652


People also ask

How do I extract color features from an image?

Method 2: Extreme points method (EPM) This method can be implemented applying the following steps: 1) Get the color image. 2) Extract the red, green, and blue components. 3) For each component initializes extreme counter to zero. 4) For each pixel in each component calculate the gradient as shown in figure (5).

How can I find out the number of colors in an image?

To calculate how many different colors can be captured or displayed, simply raise the number 2 to the power of the number of bits used to record or display the image. For example, 8-bits gives you 256 colors because 28=256. Here's a table to show you some other possibilities.


2 Answers

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
like image 100
Jake Avatar answered Sep 19 '22 07:09

Jake


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.

like image 26
unmounted Avatar answered Sep 19 '22 07:09

unmounted