【发布时间】:2010-10-26 23:39:18
【问题描述】:
我想以 (r, g, b) 元组的形式生成一个颜色规范列表,它跨越整个色谱,包含我想要的任意数量的条目。所以对于 5 个条目,我想要这样的东西:
- (0, 0, 1)
- (0, 1, 0)
- (1, 0, 0)
- (1, 0.5, 1)
- (0, 0, 0.5)
当然,如果条目多于 0 和 1 的组合,它应该转而使用分数等。这样做的最佳方法是什么?
【问题讨论】:
我想以 (r, g, b) 元组的形式生成一个颜色规范列表,它跨越整个色谱,包含我想要的任意数量的条目。所以对于 5 个条目,我想要这样的东西:
当然,如果条目多于 0 和 1 的组合,它应该转而使用分数等。这样做的最佳方法是什么?
【问题讨论】:
使用 HSV/HSB/HSL 颜色空间(三个名称大致相同)。生成 N 个均匀分布在色调空间中的元组,然后将它们转换为 RGB。
示例代码:
import colorsys
N = 5
HSV_tuples = [(x*1.0/N, 0.5, 0.5) for x in range(N)]
RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples)
【讨论】:
RGB_tuples中使用索引,在Python 3中你必须从map中创建一个list,这是一个生成器,只需list(map(lambda...))
x*1.0/N,x/N 总是产生一个浮点结果。要获得整数结果,您需要执行 x//N
0.5s 可以被其他值替换。 HSV元组是(色调、饱和度、值)元组,所有元组元素都在0到1的范围内,见en.wikipedia.org/wiki/HSL_and_HSV
调色板很有趣。你知道吗,同样亮度的绿色,比红色的感觉更强烈?看看http://poynton.ca/PDFs/ColorFAQ.pdf。如果您想使用预配置的调色板,请查看seaborn's palettes:
import seaborn as sns
palette = sns.color_palette(None, 3)
从当前调色板生成 3 种颜色。
【讨论】:
按照 kquinn 和 jhrf 的步骤 :)
对于 Python 3,可以通过以下方式完成:
def get_N_HexCol(N=5):
HSV_tuples = [(x * 1.0 / N, 0.5, 0.5) for x in range(N)]
hex_out = []
for rgb in HSV_tuples:
rgb = map(lambda x: int(x * 255), colorsys.hsv_to_rgb(*rgb))
hex_out.append('#%02x%02x%02x' % tuple(rgb))
return hex_out
【讨论】:
我根据kquinn's 的回答创建了以下函数。
import colorsys
def get_N_HexCol(N=5):
HSV_tuples = [(x*1.0/N, 0.5, 0.5) for x in xrange(N)]
hex_out = []
for rgb in HSV_tuples:
rgb = map(lambda x: int(x*255),colorsys.hsv_to_rgb(*rgb))
hex_out.append("".join(map(lambda x: chr(x).encode('hex'),rgb)))
return hex_out
【讨论】:
hex_out.append("".join(list(map(lambda x: chr(x)[2:], rgb))))?
可能不是您想要的,但这可以很好地概括您需要的多种颜色,而且非常简单。
from matplotlib import cm
colours = cm.rainbow(np.linspace(0, 1, n_colors))
【讨论】: