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?
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With