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

use*_*652 6 python python-imaging-library

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

我使用PIL,我想要一个在这个图像中使用的颜色字典,包括颜色(键)和它使用的像素点数.

怎么做?

Jak*_*ake 23

getcolors方法应该可以解决问题.查看文档.

编辑:该链接已损坏.枕头似乎是现在的首选,从PIL分叉.新文件

Image.open('file.jpg').getcolors() => a list of (count, color) tuples or None
Run Code Online (Sandbox Code Playgroud)

  • hei我得到一个奇怪的结果:它返回一个(int,int)元组的数组..我如何从一个int得到r,g,b?ps:我有一个gif文件 (4认同)
  • 您可能有一个调色板图像 - 您可以通过im.convert()将颜色通过调色板转换为一种模式,让您可以看到所有乐队 (3认同)

小智 8

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

我有这个问题,它将返回一个元组列表(数量,颜色),其中颜色只是一个数字.花了一段时间找到它,但这解决了它.

from PIL import Image
img = Image.open('image.png')
colors = img.convert('RGB').getcolors() #this converts the mode to RGB
Run Code Online (Sandbox Code Playgroud)

  • 我在RGBA模式下打开图像并尝试转换,但我仍然得到"无",即使`img.show()`显示多种颜色的图片. (3认同)
  • 没关系,如果颜色数量大于默认值 256,“maxcolors”参数将导致函数返回“None”。我只是将其设置为任意大的值,因为我不担心调色板过大(并且我无论如何,通过 alpha 值将它们过滤掉)。 (2认同)

unm*_*ted 5

我曾经用过以下几次来分析图表:

>>> 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
Run Code Online (Sandbox Code Playgroud)

即,有8个像素的rbg值(11,24,41),依此类推.

  • 所以不会让我删除一个已接受的答案,但这显然不如`getcolors`方法;) (4认同)

小智 5

请参阅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)
Run Code Online (Sandbox Code Playgroud)