在python中生成渐变色

2024-04-18 16:44:17 发布

您现在位置:Python中文网/ 问答频道 /正文

给定N个桶,我想在彩虹上连续生成颜色(其中N>;=2):

enter image description here

例如,如果n=2,则颜色为:

rgb(255,0,0) -->rgb(0,0,255)

如果n=3,则颜色为:

rgb(255,0,0) --> rgb(0,255,0) --> rgb(0,0,255)

生成这些颜色代码的好方法是什么?你知道吗


Tags: 方法gt颜色rgb颜色代码
3条回答

你的彩虹渐变平滑地改变色调从0度到240度(纯蓝色的色调)。因此,使用HSL值而不是RGB值将是最容易的,因此您可以在保持饱和度和亮度不变的同时改变色调。你知道吗

colorsys库允许在不同颜色空间之间进行转换,因此您可以根据需要沿彩虹渐变生成RGB值。hls_to_rgb函数使用介于0和1之间的浮点值,因此2/3是蓝色的色调,明亮的颜色应该具有0.5的亮度和1的饱和度。你知道吗

from colorsys import hls_to_rgb

def rainbow_color_stops(n=10, end=2/3):
    return [ hls_to_rgb(end * i/(n-1), 0.5, 1) for i in range(n) ]

结果是(r,g,b)元组的列表。你知道吗

下面是一个小脚本,使用kaya3关于HSV的建议。是个有趣的小运动。你知道吗

import colorsys
import numpy as np
from matplotlib import pyplot as plt


def spectrum(n : int):
    hsv = [(h, 1, 1) for h in np.linspace(0, 240/360, n)]
    rgb = [colorsys.hsv_to_rgb(*tup) for tup in hsv]
    defloat = lambda x: tuple((int(255 * i) for i in x))
    return [defloat(x) for x in rgb]

if __name__ == '__main__':
    n = 100
    rgb = np.array(spectrum(n))
    rgb = rgb.reshape((1, n, 3))
    rgb = np.tile(rgb, (n, 1, 1))
    plt.imshow(rgb)
    plt.show()

从而生成下图 enter image description here

使用RGB标度,红色从(255,0,0)开始,中间的绿色在(0,255,0)结束,蓝色在(0,0,255)。我们可以从(255,0,0)开始,然后“一步一步”地走到终点,这样就可以在天平中移动。你知道吗

假设从红色到绿色有256*2步(红色从256->;0到绿色从0->;256),从绿色到蓝色有256*2步。这将达到1024步。现在我们可以用1024除以我们想要的桶数,n。举个例子:

def generate_gradient_rgbs(num_buckets):
    rgb_codes = []
    step_size = 1024 / num_buckets
    for step in range(0,num_buckets):
        red = int(max(0, 255 - (step_size*step*0.5))) # step size is half of the step size since both this item goes down and the next one goes up
        blue = int(max(0, 255 - (step_size*0.5*(num_buckets-step-1))))
        green = (255 - red) if red else (255 - blue)
        rgb_codes.append((red, green, blue))
    return rgb_codes
 >>> generate_gradient_rgbs(4)
[(255, 0, 0), (127, 128, 0), (0, 128, 127), (0, 0, 255)]

当然,这是一个起点,但对于快速和肮脏的方式得到rgb的,这是一个可能的办法。你知道吗

相关问题 更多 >