Python how to get a list of colors that is used in a single image

Python how to get a list of colors that is used in a single image

I use PIL and I want to have a dictionary of colors that are used in this image, including the color (key) and the number of pixel points that it used.

How to do it?

+4
source share
4 answers

I used several times to analyze the 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 

Those. there are 8 pixels with rbg value (11, 24, 41), etc.

+3
source

The getcolors method should do the trick. See documents .

Change This link does not work. The pillow, it seems, is now going into the forehead, forked from PIL. New documents

 Image.open('file.jpg').getcolors() => a list of (count, color) tuples or None 
+21
source

I would like to add that the .getcolors () function only works if the image is in some RGB mode.

I had this problem when it was returning a list of tuples with (quantity, color), where the color was just a number. Spent me finding him, but that fixed him.

 from PIL import Image img = Image.open('image.png') colors = img.convert('RGB').getcolors() #this converts the mode to RGB 
+6
source

See https://github.com/fengsp/color-thief-py "Capturing a dominant color or 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) 
0
source

Source: https://habr.com/ru/post/1334881/


All Articles