从图像URL构建调色板

时间:2013-09-14 11:23:24

标签: python python-imaging-library palette

我正在尝试创建一个API,它将图像URL作为输入,并以JSON格式返回一个调色板作为输出。

应该是这样的:http://lokeshdhakar.com/projects/color-thief/

但应该是Python。我已经研究过PIL(Python图像库)但没有得到我想要的东西。有人能指出我正确的方向吗?

Input: Image URL
Output: List of Colors as a palette

2 个答案:

答案 0 :(得分:8)

import numpy as np
import Image

def palette(img):
    """
    Return palette in descending order of frequency
    """
    arr = np.asarray(img)
    palette, index = np.unique(asvoid(arr).ravel(), return_inverse=True)
    palette = palette.view(arr.dtype).reshape(-1, arr.shape[-1])
    count = np.bincount(index)
    order = np.argsort(count)
    return palette[order[::-1]]

def asvoid(arr):
    """View the array as dtype np.void (bytes)
    This collapses ND-arrays to 1D-arrays, so you can perform 1D operations on them.
    http://stackoverflow.com/a/16216866/190597 (Jaime)
    http://stackoverflow.com/a/16840350/190597 (Jaime)
    Warning:
    >>> asvoid([-0.]) == asvoid([0.])
    array([False], dtype=bool)
    """
    arr = np.ascontiguousarray(arr)
    return arr.view(np.dtype((np.void, arr.dtype.itemsize * arr.shape[-1])))


img = Image.open(FILENAME, 'r').convert('RGB')
print(palette(img))

palette(img)返回一个numpy数组。每行可以解释为一种颜色:

[[255 255 255]
 [  0   0   0]
 [254 254 254]
 ..., 
 [213 213 167]
 [213 213 169]
 [199 131  43]]

获得前十种颜色:

palette(img)[:10]

答案 1 :(得分:0)

color-thief库也可以在python中使用: https://github.com/fengsp/color-thief-py

示例实现:

@RequestBody myClass: MyClass
pip install colorthief
相关问题