2009-05-18 1195 views
16

我想生成(r,g,b)元組形式的顏色規範列表,其中包含儘可能多的條目,並且符合我的要求。因此,對於5項我想是這樣的:在Python中生成顏色範圍

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

當然,如果有比0和1的組合多個條目應該轉向使用分數等方面有哪些是做的最好的方法這個?

回答

38

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

7

我創建了一個基於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

繼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 
0

調色板很有趣。你知不知道,比如綠色,比綠色更強烈的感覺,比如紅色?看看http://poynton.ca/PDFs/ColorFAQ.pdf。如果您想使用預配置的調色板,看看seaborn's palettes

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

從當前調色板生成3種顏色。