如何获取图像中使用的颜色列表
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
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),等等。