用于屏幕坐标和频率字典的Python热图

彼得

只是为了好玩,我正在尝试编写鼠标跟踪脚本,我的基本部分正在工作,但是我绝对不喜欢热图。

我最初的代码是通过PIL保存图像(只是检查它是否工作),这很好,但显然它只是单个点。然后,我尝试实现自己的热图,但是发现要花费半年以上的时间才能完成一些真正基本的操作,因此也无法正常工作。

我一直在尝试使用matplotlib的其他示例,但我刚刚意识到“热图”在这种情况下的含义有所不同。

在此处输入图片说明

It's not not working, but it's also definitely not the result I was hoping to see. I'm wondering if anyone knows how I'd actually go about getting the other type of heatmap, where you get the blobs of heat? I've been googling a bunch of terms but it seems to lead back to the same 3 or so SO questions.

The data is stored in a dictionary of {(x, y): frequency}, so to get the result above I used this code (matplotlib part got from Plotting a 2D heatmap with Matplotlib):

import matplotlib.pyplot as plt

resolution = (1920, 1080)

total = []
for y in range(resolution[1]):
    row = []
    for x in range(resolution[0]):
        try:
            row.append(data[(x, y)])
        except KeyError:
            row.append(0)
    total.append(row)

plt.imshow(total, cmap='hot', interpolation='nearest')
plt.show()

The speed of that doesn't matter so much as it'll be done separately to the tracking, I'd just like something that'd initially work.

Edit: Just to clear it up a little (apologies if it wasn't clear), something like this is what I'd like: 在此处输入图片说明

Dmitry Shurov

我绘制此类热图的解决方案如下。使用数据填充2D numpy数组很容易data[(x, y)],然后使用该plot函数。请注意,您可以使用任何喜欢的颜色图,我使用代码中显示的颜色图。样品应开箱即用。

可以使用高斯模糊来实现“白底”外观。您可以调整sigma,使其更清晰或更平滑。

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy as np

import scipy.ndimage.filters as filters


def plot(data, title, save_path):
    colors = [(0, 0, 1), (0, 1, 1), (0, 1, 0.75), (0, 1, 0), (0.75, 1, 0),
              (1, 1, 0), (1, 0.8, 0), (1, 0.7, 0), (1, 0, 0)]

    cm = LinearSegmentedColormap.from_list('sample', colors)

    plt.imshow(data, cmap=cm)
    plt.colorbar()
    plt.title(title)
    plt.savefig(save_path)
    plt.close()

if __name__ == "__main__":
    w = 640
    h = 480

    data = np.zeros(h * w)
    data = data.reshape((h, w))

    # Create a sharp square peak, just for example
    for x in range(300, 340):
        for y in range(300, 340):
            data[x][y] = 100

    # Smooth it to create a "blobby" look
    data = filters.gaussian_filter(data, sigma=15)

    plot(data, 'Sample plot', 'sample.jpg')

PS cmap='jet'还可以立即提供所需的外观。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章