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)
小智 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)
我曾经用过以下几次来分析图表:
>>> 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),依此类推.
小智 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)