地球人都知道,用HSV模型定义渐近的颜色最方便,但画图时matplotlib需要用rgb或html的颜色格式。先汗了一下,然后发现没有像range一样方便的函数生成html格式的颜色list,于是只能自己写一个。因为python的中有colorsys模块,用它就可以把HSV格式转成RGB,RGB到html格式就非常easy了。因为起始和结束的颜色都从gcolor的色盘上找,所以色调H的定义域为[0,360],饱和度S的定义域为[0,100],明暗值V的定义域为[0,100]。而我们在定义渐近色的时候有两种需要,可能是沿色盘上的逆时针方向,由红->绿->蓝,也可能是想用顺时针方向,从红->蓝->绿,所以加了个clock_wise的参数,默认是False。
#!/usr/bin/python
# encoding: utf8
# filename: color_range.py
import colorsys
def hsv_to_html_range (color_start, color_end, numbers, clock_wise=False):
''' Like range(), to generate HTML RGB colors from start and end color
in HSV. The Hue domain is (0,360), the Saturation domain is (0,100),
the Value domain is (0,100).
The return is a list like ['#000000','#FFFFFF'].
'''
# here the color is (x,x,x), we need to get the interlaces of them.
color_start = [color_start[0]/360.0, color_start[1]/100.0,
color_start[2]/100.0]
color_end = [color_end[0]/360.0, color_end[1]/100.0,
color_end[2]/100.0]
if clock_wise:
color_end[0] +=1
hsv = []
# we could not use hsv = [[]] * numbers, because we use .append
# below, which exactually append to a same [].
for i in xrange(numbers):
hsv.append([])
for i in xrange(3):
inter = (color_end[i] - color_start[i] ) / (numbers - 1)
for j in xrange(numbers):
hsv[j].append(color_start[i] + j*inter)
# now we convert the hsv to rgb
#print hsv
rgb = map (lambda x: colorsys.hsv_to_rgb (x[0],x[1],x[2]) , hsv)
html_rgb = map (lambda x: "#%02X%02X%02X" % tuple( map(lambda y:
int(round(255*y)), x)), rgb)
return html_rgb[:]
发表评论