在Python中生成颜色范围

问题描述:

我想生成(r,g,b)元组形式的颜色规范列表,其中包含尽可能多的条目,并且符合我的要求。因此,对于5项我想是这样的:在Python中生成颜色范围

  • (0,0,1)
  • (0,1,0)
  • (1,0,0)
  • (1,0.5 1)
  • (0,0,0.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) 
+0

对,这就是我想要的,但我该如何生成这些元组? :) – 2009-05-18 09:32:46

+3

简单,这只是一个简单的线性系列。作为一种方法,我已经在上面提供了一些基本的示例代码。 – kquinn 2009-05-18 09:43:15

我创建了一个基于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 

继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 

调色板很有趣。你知不知道,比如绿色,比绿色更强烈的感觉,比如红色?看看http://poynton.ca/PDFs/ColorFAQ.pdf。如果您想使用预配置的调色板,看看seaborn's palettes

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

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