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

O.r*_*rka 4 python rgb graph colors matplotlib

我查看了在 Python 中生成颜色渐变,但它没有解决问题。

我通常创建随机 RGB 值来为图形着色,但我想在特定范围之间创建 RGB 渐变。在本例中,范围从 0 到 307,其中 0 是 RGB 中最深的红色,307 是 RGB 中频率最高的紫色。

在下面亚瑟王的帮助下,我使用此代码将其从深红色变为紫外线,但中间没有彩虹色。我希望输出跨越彩虹颜色的 RGB 十六进制颜色的 n 个值(在本例中为 307)列表,以便我可以在 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()
Run Code Online (Sandbox Code Playgroud)

O.r*_*rka 7

通过http://python3.codes/fractal-tree/找到了答案colorsys

货物在这里:

# 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)
Run Code Online (Sandbox Code Playgroud)

参数hue必须在 0.0 到 1.0 之间。