Python如何获取一幅图像中使用的颜色列表

Python如何获取一幅图像中使用的颜色列表,python,python-imaging-library,Python,Python Imaging Library,Python如何获取一幅图像中使用的颜色列表 我使用PIL,我想有一个图像中使用的颜色字典,包括颜色(关键点)和它使用的像素点的数量 如何做到这一点?getcolors方法应该可以做到这一点。看 编辑:该链接已断开。枕头似乎是去解放现在,从皮尔分叉 我曾多次使用类似以下的方法来分析图形: >>> from PIL import Image >>> im = Image.open('polar-bear-cub.jpg') >>> from c

Python如何获取一幅图像中使用的颜色列表

我使用PIL,我想有一个图像中使用的颜色字典,包括颜色(关键点)和它使用的像素点的数量


如何做到这一点?

getcolors方法应该可以做到这一点。看

编辑:该链接已断开。枕头似乎是去解放现在,从皮尔分叉


我曾多次使用类似以下的方法来分析图形:

>>> 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
来自PIL导入映像的
>>
>>>im=Image.open('polar-bear-cub.jpg'))
>>>从集合导入defaultdict
>>>by_color=defaultdict(int)
>>>对于im.getdata()中的像素:
...     按颜色[像素]+=1
>>>按颜色
defaultdict(,{(11,24,41):8,(53,52,58):8,(142147117):1,(121111119):1,(234228216):4

也就是说,有8个像素具有rbg值(11、24、41),依此类推。

我想补充一点,.getcolors()函数仅在图像处于某种RGB模式时才起作用

我有一个问题,它会返回一个元组列表(count,color),其中color只是一个数字

from PIL import Image
img = Image.open('image.png')
colors = img.convert('RGB').getcolors() #this converts the mode to RGB
请参阅“从图像中获取主色调或代表性调色板。使用Python和枕头”

getcolors()
None
如果图像中的颜色数大于
maxcolor
参数。该函数也仅适用于“RGB”图像。这不是很方便

另一方面,
getdata()
可以以非常方便的方式与以下各项结合使用:


我得到了一个奇怪的结果:它返回一个(int,int)元组数组..我如何从一个int中得到r,g,b?ps:我有一个gif文件你可能有一个苍白的图像--你可以做im.convert()通过调色板将颜色转换为一种模式,让您可以看到我发布此答案后7年来的所有bandsIt,这并不奇怪。Pillow似乎是从PIL派生出来的go-to-lib。因此,我不会删除一个已接受的答案,但这显然不如
getcolors
方法;)如果每次遇到黑色像素时都要执行操作(例如打印“遇到黑色像素!”),我们会怎么做?在
for pixel
循环中,我们会怎么做?我在RGBA模式下打开了一幅图像并尝试转换,但结果仍然得到
,即使
img.show()
以多种颜色显示图片。无论如何,
maxcolors
参数将导致函数返回
None
,如果颜色数大于默认值256。我只是将其设置为任意大的值,因为我不担心调色板过大(我还是用alpha值过滤掉它们)。
from PIL import Image
img = Image.open('image.png')
colors = img.convert('RGB').getcolors() #this converts the mode to RGB
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)
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