获得图像的主色

时间:2012-12-11 00:04:25

标签: python image colors python-imaging-library

如何将图像的主色显示为rgb或hexcode?

我找到了一个名为Color Thief的脚本,但它不允许图像网址只有路径。

2 个答案:

答案 0 :(得分:0)

首先使用urllib下载图片,然后删除不需要的文件:

from colorthief import ColorThief
import urllib
import os
def dominant_color_from_url(url,tmp_file='tmp.jpg'):
    '''Downloads ths image file and analyzes the dominant color'''
    urllib.urlretrieve(url, tmp_file)
    color_thief = ColorThief(tmp_file)
    dominant_color = color_thief.get_color(quality=1)
    os.remove(tmp_file)
    return dominant_color

答案 1 :(得分:0)

如果您不想下载不必要的文件,请按照以下方式进行操作:

# -*- 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))