0%

色彩采样

一个均匀从彩虹色卡上采样的小脚本,主要功能实现是 build_color() 函数,该函数有两个参数,第一个参数是采样数量,第二个参数是颜色表示形式,传入 "hex" 或不设置该参数则是返回带 # 的十六进制形式,如红色 - #ff0000, 否则返回 (r, g, b) 的十进制三元组。

彩虹色卡的七个采样点参照注释。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# 生成色卡(彩虹渐变色)
# 红 橙 黄 绿 青 蓝 紫
# r: 255, 255, 255, 0 , 0 , 0 , 139
# g: 0 , 165, 255, 255, 255, 0 , 0
# b: 0 , 0 , 0 , 0 , 255, 255, 255

def mid(left, right, cur, l_color, r_color):
""" Get middle color """
if l_color < r_color:
return int(l_color + (cur - left) * (r_color - l_color) / (right - left))
else:
return int((right - cur) * (l_color - r_color) / (right - left))

def build_color(cnt, rgb_format='hex') -> list:
""" Build uniform distribution color in rainbow colors card. """
hex_format = rgb_format == "hex"
color = list()
if cnt <= 0 or not isinstance(cnt, int):
return color
if cnt == 1:
color.append((255, 0, 0))
return color
color_step = (cnt - 1) / 6
for i in range(cnt):
idx = int(i // color_step)
if idx == 0:
r, g, b = 255, mid(0, color_step, i, 0, 165), 0
elif idx == 1:
r, g, b = 255, mid(color_step, color_step * 2, i, 165, 255), 0
elif idx == 2:
r, g, b = mid(color_step * 2, color_step * 3, i, 255, 0), 255, 0
elif idx == 3:
r, g, b = 0, 255, mid(color_step * 3, color_step * 4, i, 0, 255)
elif idx == 4:
r, g, b = 0, mid(color_step * 4, color_step * 5, i, 255, 0), 255
elif idx == 5:
r, g, b = mid(color_step * 5, cnt, i, 0, 139), 0, 255
else:
r, g, b = 139, 0, 255

if hex_format:
# save as hexadecimal (以十六进制保存)
color.append("#{:0^2}{:0^2}{:0^2}".format(*map((lambda x: x[2:]), map(hex, (r, g, b)))))
else:
# save as (r, g, b) tuple format (以元组的形式保存 r, g, b 值)
color.append((r, g, b))
return color

if __name__ == '__main__':
print(build_color(7))
--- ♥ end ♥ ---

欢迎关注我呀~