gpt4 book ai didi

colors - 色彩缩放功能

转载 作者:行者123 更新时间:2023-12-02 10:04:46 25 4
gpt4 key购买 nike

我正在尝试在表单上可视化一些值。它们的范围从 0 到 200,我希望 0 附近的那些是绿色的,当它们达到 200 时变成鲜红色。

基本上该函数应该根据输入的值返回颜色。有什么想法吗?

最佳答案

基本上,两个值之间平滑过渡的一般方法是以下函数:

function transition(value, maximum, start_point, end_point):
return start_point + (end_point - start_point)*value/maximum

鉴于此,您定义一个函数来执行三元组(RGB、HSV 等)的转换。

function transition3(value, maximum, (s1, s2, s3), (e1, e2, e3)):
r1= transition(value, maximum, s1, e1)
r2= transition(value, maximum, s2, e2)
r3= transition(value, maximum, s3, e3)
return (r1, r2, r3)

假设您有 se 三元组的 RGB 颜色,则可以按原样使用 transition3 函数。然而,通过 HSV 色彩空间会产生更“自然”的过渡。因此,考虑到转换函数(无耻地从 Python colorsys 模块中窃取并转换为伪代码:):

function rgb_to_hsv(r, g, b):
maxc= max(r, g, b)
minc= min(r, g, b)
v= maxc
if minc == maxc then return (0, 0, v)
diff= maxc - minc
s= diff / maxc
rc= (maxc - r) / diff
gc= (maxc - g) / diff
bc= (maxc - b) / diff
if r == maxc then
h= bc - gc
else if g == maxc then
h= 2.0 + rc - bc
else
h = 4.0 + gc - rc
h = (h / 6.0) % 1.0 //comment: this calculates only the fractional part of h/6
return (h, s, v)

function hsv_to_rgb(h, s, v):
if s == 0.0 then return (v, v, v)
i= int(floor(h*6.0)) //comment: floor() should drop the fractional part
f= (h*6.0) - i
p= v*(1.0 - s)
q= v*(1.0 - s*f)
t= v*(1.0 - s*(1.0 - f))
if i mod 6 == 0 then return v, t, p
if i == 1 then return q, v, p
if i == 2 then return p, v, t
if i == 3 then return p, q, v
if i == 4 then return t, p, v
if i == 5 then return v, p, q
//comment: 0 <= i <= 6, so we never come here

,您可以使用如下代码:

start_triplet= rgb_to_hsv(0, 255, 0) //comment: green converted to HSV
end_triplet= rgb_to_hsv(255, 0, 0) //comment: accordingly for red

maximum= 200

… //comment: value is defined somewhere here

rgb_triplet_to_display= hsv_to_rgb(transition3(value, maximum, start_triplet, end_triplet))

关于colors - 色彩缩放功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/168838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com