热图数据

2024-03-29 06:35:08 发布

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

我有一系列给定位置的温度。在

例如:

20 21 22 23 20
20 22 21 23 20
20 21 20 20 20
20 21 23 23 23
21 21 22 23 22

右上角的数据点表示右上角热图中的温度,而左下角-表示我要生成的热图的左下角温度。在

所以,以这些数据点为例,我将如何生成一个热图,温度越高,越红,越冷越蓝。在

我应该先把温度转换成RGB,然后再画出RGB吗?我该怎么做?在

编辑: 数组右上角(本例中为20)或[0,0]表示空间中[0,0]处的温度。我要制作的二维热图代表温度相机前面的图像。数据点是特定位置的温度。张贴不是太有帮助,因为它是基于频率,而不是转换成颜色,并根据位置绘制它。在


Tags: 数据图像编辑颜色绘制空间代表rgb
1条回答
网友
1楼 · 发布于 2024-03-29 06:35:08

您可以使用Python内置的^{}图形模块来执行如下操作。pseudocolor()函数将给定范围内的值映射到一种颜色,该颜色沿任意颜色值的调色板中的颜色插值。辅助的colorize()函数的存在是为了将从它返回的颜色值(由0到1范围内的三个浮点值组成)转换为tkinter所需的单个十六进制字符串形式。在

因为颜色的选择是由一系列颜色值控制的,所以很容易调整输出的外观。示例热图相对较小,其中的值范围也较小,因此生成的图像看起来有点“笨重”—但该方法具有良好的伸缩性,更具吸引力的结果很可能来自更大和更多样化的数据集。在

try:
    from Tkinter import *
except ModuleNotFoundError:
    from tkinter import *  # Python 3

heat_map = [[20, 21, 22, 23, 20],
            [20, 22, 21, 23, 20],
            [20, 21, 20, 20, 20],
            [20, 21, 23, 23, 23],
            [21, 21, 22, 23, 22]]

heat_min = min(min(row) for row in heat_map)
heat_max = max(max(row) for row in heat_map)

# Heatmap rgb colors in mapping order (ascending).
palette = (0, 0, 1), (0, .5, 0), (0, 1, 0), (1, .5, 0), (1, 0, 0)

def pseudocolor(value, minval, maxval, palette):
    """ Maps given value to a linearly interpolated palette color. """
    max_index = len(palette)-1
    # Convert value in range minval...maxval to the range 0..max_index.
    v = (float(value-minval) / (maxval-minval)) * max_index
    i = int(v); f = v-i  # Split into integer and fractional portions.
    c0r, c0g, c0b = palette[i]
    c1r, c1g, c1b = palette[min(i+1, max_index)]
    dr, dg, db = c1r-c0r, c1g-c0g, c1b-c0b
    return c0r+(f*dr), c0g+(f*dg), c0b+(f*db)  # Linear interpolation.

def colorize(value, minval, maxval, palette):
    """ Convert value to heatmap color and convert it to tkinter color. """
    color = (int(c*255) for c in pseudocolor(value, minval, maxval, palette))
    return '#{:02x}{:02x}{:02x}'.format(*color)  # Convert to hex string.

root = Tk()
root.title('Heatmap')

# Create and fill canvas with rectangular cells.
width, height = 400, 400  # Canvas size.
rows, cols = len(heat_map), len(heat_map[0])
rect_width, rect_height = width // rows, height // cols
border = 1  # Pixel width of border around each.

canvas = Canvas(root, width=width, height=height)
canvas.pack()
for y, row in enumerate(heat_map):
    for x, temp in enumerate(row):
        x0, y0 = x * rect_width, y * rect_height
        x1, y1 = x0 + rect_width-border, y0 + rect_height-border
        color = colorize(temp, heat_min, heat_max, palette)
        canvas.create_rectangle(x0, y0, x1, y1, fill=color, width=0)

root.mainloop()

显示:

screenshot of output window

相关问题 更多 >