利用Python实现生成颜色表(color chart)

 更新时间:2023年05月10日 09:14:16   作者:拜阳  
在做色彩相关的算法分析时候,经常需要使用规则的颜色表来进行辅助,本文就来利用numpy和opencv生成颜色表并保存为图片,需要的可以参考一下

前言

在做色彩相关的算法分析时候,经常需要使用规则的颜色表来进行辅助。下面用python(numpy和opencv)来生成颜色表并保存为图片。

有两种类型:

  • 格子形状的颜色表
  • 渐变色带

长的样子分别如下:

格子颜色表

这里需要注意,当划分的颜色数量比较少时,最好把一个颜色像素扩展成为一个格子,不然的话整个图看起来就太小了。

# -*- coding: utf-8 -*-
import cv2
import numpy as np


def generate_color_chart(block_num=18,
                         block_columns=6,
                         grid_width=32,
                         grid_height=None):
    """
    Generate color chart by uniformly distributed color indexes, only support
    8 bit (uint8).

    Parameters
    ----------
    block_num: Block number of color chart, also the number of color indexes.
    block_columns: Column number of color chart. Row number is computed by
        block_num / block_columns
    grid_width: Width of color grid
    grid_height: Height of color grid. If not set, it will equal to grid_width.
    """
    color_index = np.linspace(0, 255, block_num)
    color_index = np.uint8(np.round(color_index))

    if grid_height is None:
        grid_height = grid_width

    # compute sizes
    block_rows = np.int_(np.ceil(block_num / block_columns))
    block_width = grid_width * block_num
    block_height = grid_height * block_num
    width = block_width * block_columns
    height = block_height * block_rows
    result = np.zeros((height, width, 3), dtype=np.uint8)

    # compute red-green block, (blue will be combined afterward)
    red_block, green_block = np.meshgrid(color_index, color_index)
    red_block = expand_pixel_to_grid(red_block, grid_width, grid_height)
    green_block = expand_pixel_to_grid(green_block, grid_width, grid_height)
    rg_block = np.concatenate([red_block, green_block], axis=2)

    # combine blue channel
    for i in range(block_num):
        blue = np.ones_like(rg_block[..., 0], dtype=np.uint8) * color_index[i]
        color_block = np.concatenate([rg_block, blue[..., np.newaxis]], axis=2)
        # compute block index
        block_row = i // block_columns
        block_column = i % block_columns
        xmin = block_column * block_width
        ymin = block_row * block_height
        xmax = xmin + block_width
        ymax = ymin + block_height
        result[ymin:ymax, xmin:xmax, :] = color_block

    result = result[..., ::-1]  # convert from rgb to bgr
    return result


def expand_pixel_to_grid(matrix, grid_width, grid_height):
    """
    Expand a pixel to a grid. Inside the grid, every pixel have the same value
    as the source pixel.

    Parameters
    ----------
    matrix: 2D numpy array
    grid_width: width of grid
    grid_height: height of grid
    """
    height, width = matrix.shape[:2]
    new_heigt = height * grid_height
    new_width = width * grid_width
    repeat_num = grid_width * grid_height

    matrix = np.expand_dims(matrix, axis=2).repeat(repeat_num, axis=2)
    matrix = np.reshape(matrix, (height, width, grid_height, grid_width))
    # put `height` and `grid_height` axes together;
    # put `width` and `grid_width` axes together.
    matrix = np.transpose(matrix, (0, 2, 1, 3))
    matrix = np.reshape(matrix, (new_heigt, new_width, 1))
    return matrix


if __name__ == '__main__':
    color_chart16 = generate_color_chart(block_num=16,
                                         grid_width=32,
                                         block_columns=4)
    color_chart18 = generate_color_chart(block_num=18,
                                         grid_width=32,
                                         block_columns=6)
    color_chart36 = generate_color_chart(block_num=36,
                                         grid_width=16,
                                         block_columns=6)
    color_chart52 = generate_color_chart(block_num=52,
                                         grid_width=8,
                                         block_columns=13)
    color_chart256 = generate_color_chart(block_num=256,
                                          grid_width=1,
                                          block_columns=16)

    cv2.imwrite('color_chart16.png', color_chart16)
    cv2.imwrite('color_chart18.png', color_chart18)
    cv2.imwrite('color_chart36.png', color_chart36)
    cv2.imwrite('color_chart52.png', color_chart52)
    cv2.imwrite('color_chart256.png', color_chart256)

渐变色带

# -*- coding: utf-8 -*-
import cv2
import numpy as np


def generate_color_band(left_colors, right_colors, grade=256, height=32):
    """
    Generate color bands by uniformly changing from left colors to right
    colors. Note that there might be multiple bands.

    Parameters
    ----------
    left_colors: Left colors of the color bands.
    right_colors: Right colors of the color bands.
    grade: how many colors are contained in one color band.
    height: height of one color band.
    """
    # check and process color parameters, which should be 2D list
    # after processing
    if not isinstance(left_colors, (tuple, list)):
        left_colors = [left_colors]
    if not isinstance(right_colors, (tuple, list)):
        right_colors = [right_colors]

    if not isinstance(left_colors[0], (tuple, list)):
        left_colors = [left_colors]
    if not isinstance(right_colors[0], (tuple, list)):
        right_colors = [right_colors]

    # initialize channel, and all other colors should have the same channel
    channel = len(left_colors[0])

    band_num = len(left_colors)
    result = []
    for i in range(band_num):
        left_color = left_colors[i]
        right_color = right_colors[i]
        if len(left_color) != channel or len(right_color) != channel:
            raise ValueError("All colors should have same channel number")

        color_band = np.linspace(left_color, right_color, grade)
        color_band = np.expand_dims(color_band, axis=0)
        color_band = np.repeat(color_band, repeats=height, axis=0)
        color_band = np.clip(np.round(color_band), 0, 255).astype(np.uint8)
        result.append(color_band)
    result = np.concatenate(result, axis=0)
    result = np.squeeze(result)
    return result


if __name__ == '__main__':
    black = [0, 0, 0]
    white = [255, 255, 255]
    red = [0, 0, 255]
    green = [0, 255, 0]
    blue = [255, 0, 0]

    gray_band = generate_color_band([[0], [255]], [[255], [0]])
    color_band8 = generate_color_band(
        [black, white, red, green, blue, black, black, black],
        [white, black, white, white, white, red, green, blue]
    )

    cv2.imwrite('gray_band.png', gray_band)
    cv2.imwrite('color_band8.png', color_band8)

到此这篇关于利用Python实现生成颜色表(color chart)的文章就介绍到这了,更多相关Python颜色表内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 基于Python编写个语法解析器

    基于Python编写个语法解析器

    这篇文章主要为大家详细介绍了如何基于Python编写个语法解析器,文中的示例代码讲解详细,具有一定的学习价值,感兴趣的小伙伴可以了解一下
    2023-07-07
  • python实现RSA加密(解密)算法

    python实现RSA加密(解密)算法

    RSA是目前最有影响力的公钥加密算法,它能够抵抗到目前为止已知的绝大多数密码攻击,已被ISO推荐为公钥数据加密标准,下面通过本文给大家介绍python实现RSA加密(解密)算法,需要的朋友参考下
    2016-02-02
  • Python Pandas读取csv/tsv文件(read_csv,read_table)的区别

    Python Pandas读取csv/tsv文件(read_csv,read_table)的区别

    这篇文章主要给大家介绍了关于Python Pandas读取csv/tsv文件(read_csv,read_table)区别的相关资料,文中通过实例代码介绍的非常详细,对大家学习或者使用Pandas具有一定的参考学习价值,需要的朋友可以参考下
    2022-01-01
  • Python数据结构与算法之列表(链表,linked list)简单实现

    Python数据结构与算法之列表(链表,linked list)简单实现

    这篇文章主要介绍了Python数据结构与算法之列表(链表,linked list)简单实现,具有一定参考价值,需要的朋友可以了解下。
    2017-10-10
  • 在Python的while循环中使用else以及循环嵌套的用法

    在Python的while循环中使用else以及循环嵌套的用法

    这篇文章主要介绍了在Python的while循环中使用else以及循环嵌套的用法,是Python入门学习中的基础知识,需要的朋友可以参考下
    2015-10-10
  • Python面向对象三大特征 封装、继承、多态

    Python面向对象三大特征 封装、继承、多态

    这篇文章主要介绍了Python面向对象三大特征 封装、继承、多态,下面文章围绕Python面向对象三大特征的相关资料展开具体内容,需要的朋友可以参考一下,希望对大家有所帮助
    2021-11-11
  • PyTorch和Keras计算模型参数的例子

    PyTorch和Keras计算模型参数的例子

    今天小编就为大家分享一篇PyTorch和Keras计算模型参数的例子,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01
  • python数据解析之XPath详解

    python数据解析之XPath详解

    本篇文章主要介绍了python数据解析之xpath的基本使用详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2021-09-09
  • Python解析CDD文件的代码详解

    Python解析CDD文件的代码详解

    这篇文章主要介绍了Python解析CDD文件的方法,使用Python 脚本解析CDD文件,统一定义,一键生成,十分快捷,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-05-05
  • Python生成随机验证码代码实例解析

    Python生成随机验证码代码实例解析

    这篇文章主要介绍了Python生成随机验证码代码实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-06-06

最新评论