计算一系列值的RGB值以创建热图

2024-03-28 17:44:21 发布

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

我试图用python创建一个热图。为此,我必须为可能值范围内的每个值指定一个RGB值。我想把颜色从蓝色(最小值)改为绿色(最大值)。

下面的图片示例解释了我对颜色组成的看法:我们有1(纯蓝色)到3(纯红色)的范围,2介于绿色之间。

color composition RGB in range(1-3)

我读了关于线性插值的文章,写了一个函数(或多或少)处理最小值和最大值之间某个值的计算,并返回一个RGB元组。它使用ifelif条件(这并不能让我完全满意):

def convert_to_rgb(minimum, maximum, value):
    minimum, maximum = float(minimum), float(maximum)    
    halfmax = (minimum + maximum) / 2
    if minimum <= value <= halfmax:
        r = 0
        g = int( 255./(halfmax - minimum) * (value - minimum))
        b = int( 255. + -255./(halfmax - minimum)  * (value - minimum))
        return (r,g,b)    
    elif halfmax < value <= maximum:
        r = int( 255./(maximum - halfmax) * (value - halfmax))
        g = int( 255. + -255./(maximum - halfmax)  * (value - halfmax))
        b = 0
        return (r,g,b)

不过,我想知道是否可以在不使用if条件的情况下为每个颜色值编写一个函数。有人知道吗?非常感谢!


Tags: 函数returnifvalue颜色rgbfloat条件
3条回答

这里有另一种方法,虽然不尽可能短,但更一般,因为它没有硬编码为您的特定颜色集。这意味着它还可以用于在任意颜色的可变大小调色板上线性插值指定范围的值。

还要注意的是,颜色可以在其他颜色空间中进行插值,从而得到比其他颜色更令人满意的结果。这在我提交给一个名为Range values to pseudocolor的相关问题的两个独立答案中得到的不同结果中得到了说明。

import sys
EPSILON = sys.float_info.epsilon  # Smallest possible difference.

def convert_to_rgb(minval, maxval, val, colors):
    # "colors" is a series of RGB colors delineating a series of
    # adjacent linear color gradients between each pair.
    # Determine where the given value falls proportionality within
    # the range from minval->maxval and scale that fractional value
    # by the total number in the "colors" pallette.
    i_f = float(val-minval) / float(maxval-minval) * (len(colors)-1)
    # Determine the lower index of the pair of color indices this
    # value corresponds and its fractional distance between the lower
    # and the upper colors.
    i, f = int(i_f // 1), i_f % 1  # Split into whole & fractional parts.
    # Does it fall exactly on one of the color points?
    if f < EPSILON:
        return colors[i]
    else:  # Otherwise return a color within the range between them.
        (r1, g1, b1), (r2, g2, b2) = colors[i], colors[i+1]
        return int(r1 + f*(r2-r1)), int(g1 + f*(g2-g1)), int(b1 + f*(b2-b1))

if __name__ == '__main__':
    minval, maxval = 1, 3
    steps = 10
    delta = float(maxval-minval) / steps
    colors = [(0, 0, 255), (0, 255, 0), (255, 0, 0)]  # [BLUE, GREEN, RED]
    print('  Val       R    G    B')
    for i in range(steps+1):
        val = minval + i*delta
        r, g, b = convert_to_rgb(minval, maxval, val, colors)
        print('{:.3f} -> ({:3d}, {:3d}, {:3d})'.format(val, r, g, b))

数值输出:

  Val       R    G    B
1.000 -> (  0,   0, 255)
1.200 -> (  0,  50, 204)
1.400 -> (  0, 101, 153)
1.600 -> (  0, 153, 101)
1.800 -> (  0, 204,  50)
2.000 -> (  0, 255,   0)
2.200 -> ( 51, 203,   0)
2.400 -> (102, 152,   0)
2.600 -> (153, 101,   0)
2.800 -> (203,  51,   0)
3.000 -> (255,   0,   0)

下面是显示为水平渐变的输出:

horizontal gradient generated with function in answer

def rgb(minimum, maximum, value):
    minimum, maximum = float(minimum), float(maximum)
    ratio = 2 * (value-minimum) / (maximum - minimum)
    b = int(max(0, 255*(1 - ratio)))
    r = int(max(0, 255*(ratio - 1)))
    g = 255 - b - r
    return r, g, b

您通常可以将带有索引的if消除为两个值的数组。Python缺少一个三元条件运算符,但这是有效的:

r = [red_curve_1, red_curve_2][value>=halfmax]
g = [green_curve_1, green_curve_2][value>=halfmax]
b = [blue_curve_1, blue_curve_2][value>=halfmax]

*_curve_1*_curve_2表达式分别替换为中点左侧或右侧的常数、斜率或曲线。

我将把这些替代品留给你,但是例如:

  • red_curve_1blue_curve_2只是0
  • green_curve_1255*(value-minimum)/(halfmax-minimum)
  • 等等

相关问题 更多 >