首页 > 编程语言 >[python]第三方库ColorThief的使用

[python]第三方库ColorThief的使用

时间:2022-12-25 10:33:06浏览次数:54  
标签:palette 颜色 python ColorThief color 提取 quality 第三方

介绍了python第三方库ColorThief的使用方法并配有简单代码。

目录

什么是Color Thief?

从图像中提取调色板的模块。pypi链接

主要通过自定义ColorThief类,实现提取图片的一种主要颜色或者提取图片的主色调。

如何安装Color Thief?

  $ pip install colorthief

如何使用Color Thief?

导入

from colorthief import ColorThief

实例化ColorThief

img_path=“”  # str | 图片路径 | e.g. “1.jpg”
color_thief = ColorThief(img_path)  # 得到ColorThief的实例,color_thief

提取图片的一种主要颜色

dominant_color = color_thief.get_color()
print(dominant_color)

提取图片的主色调

palette = color_thief.get_palette()
print(palette)

进阶使用Color Thief

通过以上版块我们掌握了Color Thief库的基本使用方法,下面我们更进一步地探索其使用方法。

API

class ColorThief(object):
    def __init__(self, file):
        """ Create one color thief for one image.
        :param file: A filename (string) or a file object. The file object must implement `read()`, `seek()`, and `tell()` methods, and be opened in binary mode.
        """
        """ 为一张图片创建ColorThief实例
        :参数 file: 可以是图片的文件路径(str类型)或者是自定义文件类的一个实例。 如果是后者,那么这个实例必须要有`read()`, `seek()`, 和 `tell()`三个方法,并且能够在二进制模式下打开。
        """
        
        pass

    def get_color(self, quality=10):
        """ Get the dominant color.
            :param quality: quality settings, 1 is the highest quality, the bigger the number, the faster a color will be returned but the greater the likelihood that it will not be the visually most dominant color.
            :return tuple: (r,g,b)
        """
        """ 提取图片中的主要颜色。
            :参数 quality: 质量设定,1是最高质量。数字越大,提取速度越快,但也越有可能提取的颜色不是图片上看起来的主要颜色。
            :返回值 tuple: 一个元祖,包含三个元素,分别是主题色的r,g,b三通道对应数值。 
        """    
        pass

    def get_palette(self, color_count=10, quality=10):
        """ Build a color palette.
            We are using the median cut algorithm to cluster similar colors.
            :param color_count: the size of the palette, max number of colors
            :param quality: quality settings, 1 is the highest quality, the bigger the number, the faster the palette generation, but the greater the likelihood that colors will be missed.
            :return list: a list of tuple in the form (r, g, b)
        """
        """ 为图片计算它的主色调(color palette调色板)。我们使用的是中位切分算法(median cut 
            algorithm)来把相似的颜色聚类。
            :参数 color_count: 调色板的大小,也就是最多提取多少种颜色。
            :参数 quality: 质量设定,1是最高质量。数字越大,计算出主色调的速度越快,但也越有可能丢失部分颜色。
            :返回值 list: 一个列表,其每个元素是一个元祖,由主题色的r,g,b三通道对应数值组成。
        """
        pass

提取主要颜色

写了个简短的代码测试一下参数quality的影响,测试代码如下:

from colorthief import ColorThief
import time
from PIL import Image
import matplotlib.pyplot as plt

img_path="1.png"
color_thief = ColorThief(img_path)
quality_list=[10,20,30,40,50,60,70,80] #提取主要颜色的质量设定值
results=[]
n_colors=len(quality_list)

fig, axs=plt.subplots(1,n_colors,figsize=(20,3))

for i in range(0,n_colors,1):
    start=time.time()
    quality=quality_list[i]
    # i从0开始,quality应该是1,所以注意quality=i+1
    dominant_color = color_thief.get_color(quality=quality)
    end=time.time()
    t=round(end-start,3)
    results.append((quality,dominant_color,t))
print(results)

for i in range(0,n_colors,1):
    dom_color=Image.new('RGB',(3,3),results[i][1])
    ax=axs[i]
    q=results[i][0]
    t=results[i][2]
    ax.set_title(str(q)+"|"+str(t),fontsize=10)
    # 去掉刻度
    ax.set_xticks([])
    ax.set_yticks([])
    # 去掉坐标轴
    ax.axis('off')
    ax.imshow(dom_color)
    
plt.savefig(f"dominant_color_{img_path}")
plt.show()

测试图片1: 分辨率768*1600
图片

测试结果1:
图片

quality 时间(s) 颜色(256rgb)
10 1.317 43,29,45
20 0.850 43,29,45
30 0.716 43,29,45
40 0.642 43,29,45
50 0.592 43,29,45
60 0.606 43,29,45
70 0.508 43,29,45
80 0.558 43,29,45

测试图片2: 分辨率1080*2340
图片

测试结果2:
图片

quality 时间(s) 颜色(256rgb)
10 2.103 210,121,164
20 1.297 210,121,164
30 1.508 210,121,164
40 0.919 210,121,164
50 0.841 210,121,164
60 0.743 36,87,146
70 0.744 210,121,164
80 0.729 36,87,146

可以看到quality在1-60之间,结果基本不变,但面对不同颜色出现频率接近的情况就会出现一定的判断错误。其实我个人觉得只提取一种主要颜色本来就挺难敲定说某个颜色就是主要颜色,毕竟如果是个windows四色图标,那大概得是四种主要颜色。

提取主色调

from colorthief import ColorThief
import time
from PIL import Image
import matplotlib.pyplot as plt

img_path="2.png"
color_thief = ColorThief(img_path)
quality=50 #提取主要颜色的质量设定值

fig, axs=plt.subplots(3,3,figsize=(5,5))

palette = color_thief.get_palette(color_count=10,quality=quality)

for i in range(0,9,1):
    rgb=palette[i]
    color=Image.new('RGB',(3,3),rgb)
    ax=axs[int(i/3),i%3]
    ax.set_title(str(rgb),fontsize=10)
    # 去掉刻度
    ax.set_xticks([])
    ax.set_yticks([])
    # 去掉坐标轴
    ax.axis('off')
    ax.imshow(color)
    
plt.savefig(f"palette_{img_path}")
plt.show()

测试图片1: 分辨率768*1600
图片

测试结果1:
图片

测试图片2: 分辨率1080*2340
图片

测试结果2:
图片

需要注意的是get_palette的参数color_count按照注释看应该是最多提取颜色数量,所以有一定可能实际提取颜色数量小于这个值。
比如说我拿了一张纯红的图片,color_count设置为5,实际返回5个颜色,但如果设置为10,就会只返回9个颜色。

深入理解

对于调色板Palette或者叫做颜色查找表,以及中位切分算法(median cut algorithm),可以参考这个链接进一步理解具体原理。

Q&A

  1. 上述代码使用测试平台?

    Python-3.7.9 + colorthief-0.2.1

    笔记本MacBookAir8,双核[email protected]

  2. (待补充)

致谢

感谢Lokesh Dhakar的原创内容GitHub仓库

标签:palette,颜色,python,ColorThief,color,提取,quality,第三方
From: https://www.cnblogs.com/fish-touching/p/17003733.html

相关文章