首页 > 解决方案 > 如何通过调用 matplotlib imshow 两次为同一斧头覆盖热图?

问题描述

最近在推特上发布了一段激动人心的动画:https ://twitter.com/thomas_rackow/status/1392509885883944960 。其中一位作者在此 Jupyter Notebook https://nbviewer.jupyter.org/github/koldunovn/FESOM_SST_shaded_by_U/blob/main/FESOM_SST_shaded_by_U.ipynb中解释了 如何创建框架。

imshow与此笔记本显示的简单代码相关,我的问题是:当我们为同一个调用两次时ax

ax.imshow(np.flipud(sst.sst.values), cmap=cm.RdBu_r,  vmin=12, vmax=24)
ax.imshow(np.flipud(u.u_surf.values), alpha=0.3, cmap=cm.gray, vmin=-.3, vmax=0.3) 

什么操作在幕后执行 matplotlib 以获得分层图像?我在 Open CV - Python 中使用了 alpha 混合,但在这里它从两个相同形状的数组(1000、1000)开始,并且 viaax.imshow为这两个数组调用了两次,它显示了结果图像。我想知道这怎么可能。涉及图像之间的哪些算术运算?我搜索了 matplotlib github 存储库以了解发生了什么,但我找不到相关的东西。

标签: imagematplotlib

解决方案


我成功地说明了这两个imshow(s)隐藏了两个图像的 alpha 混合。

import numpy as np
import xarray as xr
import matplotlib.pyplot as plt
import matplotlib.cm as cm

sst = xr.open_dataset('GF_FESOM2_testdata/sst.nc')
u = xr.open_dataset('GF_FESOM2_testdata/u_surf.nc')
v = xr.open_dataset('GF_FESOM2_testdata/v_surf.nc')

#Define the heatmap from SST-data and extract the array representing it as an image:

fig1, ax1 = plt.subplots(1, 1,
            constrained_layout=True,
            figsize=(10,  10))
f1 = ax1.imshow(np.flipud(sst.sst.values), cmap=cm.RdBu_r,  vmin=12, vmax=24)
ax1.axis('off');
arr1 = f1.make_image('notebook')[0] #array representing the above image

#Repeat the same procedure for  u-data set:

fig2, ax2 = plt.subplots(1, 1,
            constrained_layout=True,
            figsize=(10,  10))
f2 = ax2.imshow(np.flipud(u.u_surf.values),  cmap=cm.gray, vmin=-0.3, vmax=0.3)
ax2.axis('off');

arr2 = f2.make_image("notebook")[0]
#alpha blending of the two images amounts to a convex combination of the associated arrays
alpha1= 1  # background image alpha
alpha2 = 0.3  #foreground image alpha
arr = np.asarray((alpha2*arr2 + alpha1*(1-alpha2)*arr1)/(alpha2+alpha1*(1-alpha2)), dtype=np.uint8)


fig, ax = plt.subplots(1, 1,
            constrained_layout=True,
            figsize=(10,  10))
ax.imshow(np.flipud(arr))
ax.axis('off');

推荐阅读