【问题标题】:Build a color palette from image URL从图像 URL 构建调色板
【发布时间】:2013-09-14 11:23:24
【问题描述】:

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

它应该像这样工作:http://lokeshdhakar.com/projects/color-thief/

但应该在 Python 中。我研究了 PIL(Python 图像库),但没有得到我想要的。有人能指出我正确的方向吗?

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

【问题讨论】:

  • I have looked into PIL (Python Image Library) but didn't get what I want - 需要详细说明吗?
  • 由于我是 PIL 的新手,我找不到完成此任务所需的工具。

标签: python python-imaging-library palette


【解决方案1】:
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]

【讨论】:

  • 好吧,我想获得前 10 种主​​要颜色。如何从输出中检索它?
  • @ManishPatel:看看stackoverflow.com/questions/9448029/…。如果这不能回答您的问题,请发布一个新问题,其中包含您的输入样本(它是数组、列表还是 int?)和预期的输出。
  • 这非常好,而且速度很快。您能建议一种将其转换为 RGBa 图像的方法吗?您现在有一个形状为 (nbcolors,4) 的调色板,我该如何制作 (nbcolors,1,4) 以具有大小为 nbcolors x 1 像素和 4 个通道的图像?
  • @ZloySmiertniy:给定p = palette(img) 形状为(nbcolors, 4),您可以使用p[:,None,:]p[:,np.newaxis,:],或p.reshape(-1, 1, 4) 来获得形状为(nbcolors, 1, 4) 的数组。 (reshape 将自动将负 1 替换为您唯一合理的选择)。
  • @unutbu 谢谢,我用的是 np.expand_dims(p, axis=0) 很高兴看到许多可能的方法
【解决方案2】:

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

示例实现:

pip install colorthief
# -*- coding: utf-8 -*-

import sys

if sys.version_info < (3, 0):
    from urllib2 import urlopen
else:
    from urllib.request import urlopen

import io

from colorthief import ColorThief


fd = urlopen('http://lokeshdhakar.com/projects/color-thief/img/photo1.jpg')
f = io.BytesIO(fd.read())
color_thief = ColorThief(f)
print(color_thief.get_color(quality=1))
print(color_thief.get_palette(quality=1))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-23
    • 2014-12-29
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 2011-04-20
    • 2012-05-21
    • 2015-01-09
    相关资源
    最近更新 更多