制作一个带有 2d 点和 2 张图像的热图

问题描述

大家好, 我正在尝试创建一个热图,给定一组从 CSV 文件提取的 x、y 坐标对。我正在使用 numpy.histogram2d 来绘制它,热图给了我正确的结果,但我需要将它叠加在另一个图像上。我分享我的代码

Here 是 CSV

csv = pd.read_csv("../test2.csv")
#Gets the centroid of the coords
csv["x"] = (combined_csv["x_min"]+(combined_csv["x_max"]-combined_csv["x_min"])/2).astype(int) 
csv["y"] = (combined_csv["y_min"]+(combined_csv["y_max"]-combined_csv["y_min"])/2).astype(int)
am = csv[(csv["tracking_id"] != 7) &(csv["tracking_id"] != 28)] #Some filters

#Taken from another question
def myplot(x,y,s,bins=1000):
    heatmap,xedges,yedges = np.histogram2d(x,bins=bins,range=[[0,960],[0,480]])
    heatmap = gaussian_filter(heatmap,sigma=s)
    extent = [xedges[0],xedges[-1],yedges[0],yedges[-1]]
    return heatmap.T,extent
img,extent = myplot(am["x"],am["y_max"],16,200)
plt.imshow(img,extent=extent,origin='upper',cmap=cm.jet)

之前的代码给了我这张图片

Heatmap with correct extents

我将 x 的范围设置为 0 到 480,y 的范围为 0 和 960,因为目标图像具有那个大小,但是这样做时,histogram2d 会返回直方图矩阵 h,即 200x200,然后我使用 matplotlib 进行绘图它和这将我正确地绘制在 x 的 0-480 和 y 的 0-960 范围内,我需要的是保存所述图像,在 480x960 像素大小中保留尽可能多的信息,然后将其与目标图像一起添加使用本教程 how to superimpose heatmap on a base image?

final_img = cv2.addWeighted (heatmap_img,0.5,image,0)

为了创造这样的东西

Example of what i wanted

但是图像和直方图与我想要的尺寸不匹配。 这是目标图像

Target image

解决方法

好的,所以我通过下一个代码修复了错误,在同一个图中打印两个图像

base_image = image
sigma = 8
fig,ax = plt.subplots(1,1,figsize = (20,16))
heatmap,xedges,yedges = np.histogram2d(am["x"],am["y"],bins=200,range=[[0,960],[0,480]])
heatmap = gaussian_filter(heatmap,sigma=sigma)
extent = [xedges[0],xedges[-1],yedges[-1],yedges[0]]
img = heatmap.T
ax.imshow(img,extent=extent,cmap=cm.jet)
ax.imshow(base_image,alpha = 0.5)
ax.set_xlim(0,960)
ax.set_ylim(480,0)
ax.axes.get_yaxis().set_visible(False)
ax.axes.get_xaxis().set_visible(False)
plt.subplots_adjust(left=0,bottom=0,right=1,top=1,wspace=0,hspace=0)
plt.savefig("heatmap_final.png",bbox_inches='tight')
plt.show()
plt.close(fig)