翼度科技»论坛 编程开发 python 查看内容

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

7

主题

7

帖子

21

积分

新手上路

Rank: 1

积分
21
前言

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

  • 格子形状的颜色表
  • 渐变色带
长的样子分别如下:



格子颜色表

这里需要注意,当划分的颜色数量比较少时,最好把一个颜色像素扩展成为一个格子,不然的话整个图看起来就太小了。
  1. # -*- coding: utf-8 -*-
  2. import cv2
  3. import numpy as np


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

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

  21.     if grid_height is None:
  22.         grid_height = grid_width

  23.     # compute sizes
  24.     block_rows = np.int_(np.ceil(block_num / block_columns))
  25.     block_width = grid_width * block_num
  26.     block_height = grid_height * block_num
  27.     width = block_width * block_columns
  28.     height = block_height * block_rows
  29.     result = np.zeros((height, width, 3), dtype=np.uint8)

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

  35.     # combine blue channel
  36.     for i in range(block_num):
  37.         blue = np.ones_like(rg_block[..., 0], dtype=np.uint8) * color_index[i]
  38.         color_block = np.concatenate([rg_block, blue[..., np.newaxis]], axis=2)
  39.         # compute block index
  40.         block_row = i // block_columns
  41.         block_column = i % block_columns
  42.         xmin = block_column * block_width
  43.         ymin = block_row * block_height
  44.         xmax = xmin + block_width
  45.         ymax = ymin + block_height
  46.         result[ymin:ymax, xmin:xmax, :] = color_block

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


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

  53.     Parameters
  54.     ----------
  55.     matrix: 2D numpy array
  56.     grid_width: width of grid
  57.     grid_height: height of grid
  58.     """
  59.     height, width = matrix.shape[:2]
  60.     new_heigt = height * grid_height
  61.     new_width = width * grid_width
  62.     repeat_num = grid_width * grid_height

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


  70. if __name__ == '__main__':
  71.     color_chart16 = generate_color_chart(block_num=16,
  72.                                          grid_width=32,
  73.                                          block_columns=4)
  74.     color_chart18 = generate_color_chart(block_num=18,
  75.                                          grid_width=32,
  76.                                          block_columns=6)
  77.     color_chart36 = generate_color_chart(block_num=36,
  78.                                          grid_width=16,
  79.                                          block_columns=6)
  80.     color_chart52 = generate_color_chart(block_num=52,
  81.                                          grid_width=8,
  82.                                          block_columns=13)
  83.     color_chart256 = generate_color_chart(block_num=256,
  84.                                           grid_width=1,
  85.                                           block_columns=16)

  86.     cv2.imwrite('color_chart16.png', color_chart16)
  87.     cv2.imwrite('color_chart18.png', color_chart18)
  88.     cv2.imwrite('color_chart36.png', color_chart36)
  89.     cv2.imwrite('color_chart52.png', color_chart52)
  90.     cv2.imwrite('color_chart256.png', color_chart256)
复制代码
渐变色带
  1. # -*- coding: utf-8 -*-
  2. import cv2
  3. import numpy as np


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

  8.     Parameters
  9.     ----------
  10.     left_colors: Left colors of the color bands.
  11.     right_colors: Right colors of the color bands.
  12.     grade: how many colors are contained in one color band.
  13.     height: height of one color band.
  14.     """
  15.     # check and process color parameters, which should be 2D list
  16.     # after processing
  17.     if not isinstance(left_colors, (tuple, list)):
  18.         left_colors = [left_colors]
  19.     if not isinstance(right_colors, (tuple, list)):
  20.         right_colors = [right_colors]

  21.     if not isinstance(left_colors[0], (tuple, list)):
  22.         left_colors = [left_colors]
  23.     if not isinstance(right_colors[0], (tuple, list)):
  24.         right_colors = [right_colors]

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

  27.     band_num = len(left_colors)
  28.     result = []
  29.     for i in range(band_num):
  30.         left_color = left_colors[i]
  31.         right_color = right_colors[i]
  32.         if len(left_color) != channel or len(right_color) != channel:
  33.             raise ValueError("All colors should have same channel number")

  34.         color_band = np.linspace(left_color, right_color, grade)
  35.         color_band = np.expand_dims(color_band, axis=0)
  36.         color_band = np.repeat(color_band, repeats=height, axis=0)
  37.         color_band = np.clip(np.round(color_band), 0, 255).astype(np.uint8)
  38.         result.append(color_band)
  39.     result = np.concatenate(result, axis=0)
  40.     result = np.squeeze(result)
  41.     return result


  42. if __name__ == '__main__':
  43.     black = [0, 0, 0]
  44.     white = [255, 255, 255]
  45.     red = [0, 0, 255]
  46.     green = [0, 255, 0]
  47.     blue = [255, 0, 0]

  48.     gray_band = generate_color_band([[0], [255]], [[255], [0]])
  49.     color_band8 = generate_color_band(
  50.         [black, white, red, green, blue, black, black, black],
  51.         [white, black, white, white, white, red, green, blue]
  52.     )

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

来源:https://www.jb51.net/article/283828.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具