Python生成特定风格的配色组合

需求描述

最近有一个需求,在图像上画目标框的时候,有些类别的框需要用冷色调,有些类别的框需要用暖色调,但是不同实例的框颜色需要有差异。如果用随机数生成颜色,有时候不够美观,所以就想到从 matplotlib 的 colormap 中选取一些漂亮的颜色组合。

简单来说,就是写一个函数,用来生成指定数量的颜色列表,所有颜色从某一指定风格的色板中提取

例如下图:从这个风格的colormap中,等间隔提取若干个颜色。
在这里插入图片描述
也可以从冷色调、暖色调中提取所需要的颜色数值列表:
在这里插入图片描述

代码示例

主体思路就是,选择一个你觉得美观的 colormap 色板1,根据你需要生成的配色数量,用等间隔或者其他采样策略,去 colormap 去提取 rgb 颜色数值,顺便转成十六进制的颜色码2,输出 rgb_list 和 hex_list。

def RGB_to_Hex(rgb):
    """
    RGB格式颜色转换为16进制颜色格式
    Args:
        rgb: tuple

    Returns:
        color: str
    """
    RGB = list(rgb)
    color = '#'
    for i in RGB:
        num = int(i)
        color += str(hex(num))[-2:].replace('x', '0').upper()
    return color
    
def generate_colors(N=12,colormap='hsv'):
    """
    生成颜色列表
    Args:
        N: 生成颜色列表中的颜色个数
        colormap: plt中的色表,如'cool'、'autumn'等

    Returns:
        rgb_list: list, 每个值(r,g,b)在0~255范围
        hex_list: list, 每个值为十六进制颜色码类似:#FAEBD7
    """
    step = max(int(255/N),1)
    cmap = plt.get_cmap(colormap)
    rgb_list = []
    hex_list = []
    for i in range(N):
        id = step*i # cmap(int)->(r,g,b,a) in 0~1
        id = 255 if id>255 else id
        rgba_color = cmap(id)
        rgb = [int(d*255) for d in rgba_color[:3]]
        rgb_list.append(tuple(rgb))
        hex_list.append(RGB_to_Hex(rgb))
    return rgb_list,hex_list
    
# 生成 6个冷色调的颜色
rgb_list,hex_list = generate_colors(6,'cool')
print(rgblist)
print(hexlist)

这段程序会输出我们需要的6个冷色调颜色,一个是rgb列表,一个是16进制颜色码列表:
在这里插入图片描述
代码中 cmap = plt.get_cmap(colormap) 可以获取matplotlib里的指定调色板(colormap)

我们按照所需的颜色数量N,等间隔去调色板中取色:rgba_color = cmap(step*i)
在这里插入图片描述
对tuple中的每个值乘以255,就能得到 r,g,b,a 的数值。

色板参考

matplotlib中的colormaps1
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

参考链接


  1. https://matplotlib.org/3.3.0/gallery/color/colormap_reference.html#sphx-glr-gallery-color-colormap-reference-py ↩︎ ↩︎

  2. https://blog.csdn.net/sinat_37967865/article/details/93203689 ↩︎

猜你喜欢

转载自blog.csdn.net/Bit_Coders/article/details/121383126