2011-01-10 34 views
4

Python中如何获取一个图像Python中如何获取一个图像

我用PIL,我想有颜色的字典,在用于使用的颜色列表颜色列表此图像包括其使用的颜色(键)和像素点的数量。

如何做到这一点?

回答

3

我已经使用类似下面的几次来分析图:

>>> 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 

即,有8个像素与RBG值(11,24,41),等等。

21

getcolors方法应该做的伎俩。请参阅the docs

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

嘿嘿,我得到一种怪异的结果:它返回(int数组, int)元组..我怎么能得到r,g,b从一个单一的int? PS:我有一个GIF文件 – nkint 2011-02-27 14:39:05

+3

你可能有一个调色板图像 - 你可以做im.convert()通过调色板的颜色转换成一个模式,让你看到所有的乐队 – jlivni 2012-07-16 18:55:56

+0

链接文档被打破了。 – 2018-02-13 00:33:09

6

我想补充一点,.getcolors()函数只适用于图像处于某种类型的RGB模式。

我有这个问题,它会返回一个元组列表(颜色只是一个数字)的元组列表。花了我一段时间才找到它,但这固定了它。

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

https://github.com/fengsp/color-thief-py“抓斗从图像中主色或者代表色调色板使用Python和枕头”

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)