在Python中生成颜色范围

时间:2009-05-18 09:24:32

标签: python colors

我想以(r,g,b)元组的形式生成颜色规范列表,这些颜色规范跨越整个颜色范围,包含我想要的任意数量的条目。所以对于5个条目,我想要类似的东西:

  • (0,0,1)
  • (0,1,0)
  • (1,0,0)
  • (1,0.5,1)
  • (0,0,0.5)

当然,如果条目多于0和1的组合,则应转向使用分数等。最好的方法是什么?

4 个答案:

答案 0 :(得分:42)

使用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)

答案 1 :(得分:8)

我根据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

答案 2 :(得分:5)

调色板很有趣。您是否知道绿色相同的亮度比红色更强烈?看看http://poynton.ca/PDFs/ColorFAQ.pdf。如果您想使用预配置的调色板,请查看seaborn's palettes

import seaborn as sns
palette = sns.color_palette(None, 3)

从当前调色板生成3种颜色。

答案 3 :(得分:4)

遵循kquinn&jsf和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