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

20 投票
5 回答
48105 浏览
提问于 2025-04-16 09:41

Python 如何获取一张图片中使用的颜色列表

我在用PIL这个库,我想要得到一个字典,里面包含这张图片中使用的颜色(作为键)和每种颜色所占的像素点数量。

该怎么做呢?

5 个回答

12

我想补充一下,.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
32

getcolors 方法应该可以解决这个问题。你可以查看 这个文档

编辑: 那个链接坏掉了。现在 Pillow 似乎是最常用的库,它是从 PIL 分出来的。你可以查看 新的文档

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

我之前用过类似下面的代码来分析图形:

>>> 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),等等。

撰写回答