如何在Python 2.7中创建rgb彩虹渐变?

时间:2015-08-17 20:43:39

标签: python matplotlib graph colors rgb

我看了Generating color gradient in Python,但它没有做到这一点

我通常为着色图创建随机rgb值,但我想在特定范围之间创建渐变rgb。在这种情况下,范围将从[0-307]开始,其中0将是RGB中最暗的红色,307将是RGB中最高的紫色频率

在下面的亚瑟王的帮助下,我已经使用这个代码将它从最暗的红色变为紫外线,但两者之间没有彩虹色。我想输出一个n个值的列表(在这种情况下是307)rgb hex颜色跨越彩虹的颜色,所以我可以在matplotlib中绘制它们

def hex_to_RGB(hex):
    ''' "#FFFFFF" -> [255,255,255] '''
    # Pass 16 to the integer function for change of base
    return [int(hex[i:i+2], 16) for i in range(1,6,2)]



def linear_gradient(start_hex, finish_hex="#FFFFFF", n=307):
    ''' returns a gradient list of (n) colors between
        two hex colors. start_hex and finish_hex
        should be the full six-digit color string,
        inlcuding the number sign ("#FFFFFF") '''
    # Starting and ending colors in RGB form
    s = hex_to_RGB(start_hex)
    f = hex_to_RGB(finish_hex)
    # Initilize a list of the output colors with the starting color
    RGB_list = [s]
    # Calcuate a color at each evenly spaced value of t from 1 to n
    for t in range(1, n):
        # Interpolate RGB vector for color at the current value of t
        curr_vector = [int(s[j] + (float(t)/(n-1))*(f[j]-s[j])) for j in range(3)]
        # Add it to our list of output colors
        RGB_list.append(curr_vector)

    return RGB_list

start = '#660000'   
end = '#7f1ae5'.upper()

2 个答案:

答案 0 :(得分:4)

找到colorsys的答案 http://python3.codes/fractal-tree/

货物在这里:

# https://docs.python.org/2/library/colorsys.html
(r, g, b) = colorsys.hsv_to_rgb(hue, 1.0, 1.0)
R, G, B = int(255 * r), int(255 * g), int(255 * b)

参数hue必须介于0.0到1.0之间。

答案 1 :(得分:2)

像这样的东西 - > http://bsou.io/posts/color-gradients-with-python 应该能够帮助你。它是如何使用Python创建颜色渐变的指南,它对该过程有相当深入的了解。