不同尺寸图像的共享 matplotlib 轴(链接缩放和平移)

Shared matplotlib axes for images with different sizes (Linked zooming and panning)

我用 matplotlib imshow() 显示了两张图片。这些图像彼此相关,因此在缩放或平移时它们的行为应该相同。当它们具有相同的分辨率时,这很好用。但是当他们的分辨率不同时,共享轴会以一种(对我来说)意想不到的方式起作用。 假设这是我的两张图像,一张是二维高斯图像,一张是 600x400 分辨率,另一张是 300x200 分辨率。 当我共享轴时,会发生这种情况:

但是,我希望输出像第一种情况一样,但是在缩放或平移时,应该相应地操作第二个图像。像这样,我希望能够得到这样的输出: 我知道这些轴并没有真正共享,但它们应该看起来像这样。

我尝试设置双轴(比例减半),但就我的问题而言,这不是很成功。

重现我附加的图像并玩转的代码:

import matplotlib.pyplot as plt
import numpy as np
from scipy.ndimage import zoom

w, h = 600, 400  # original resolution width & height
x, y = np.meshgrid(np.arange(w), np.arange(h))

gaussian = np.exp(-(np.sqrt((x - w/2) ** 2 + (y - h/2) ** 2) ** 2 / (2.0 * 100 ** 2)))  # 600x400
downsampled = zoom(gaussian, 0.5)  # 300x200

ax_big = plt.subplot2grid((1, 2), (0, 0))
ax_big.imshow(gaussian, cmap='turbo')

ax_small = plt.subplot2grid((1, 2), (0, 1))
# I want something like this:
# ax_small = plt.subplot2grid((1, 2), (0, 1), sharex=ax_big, sharey=ax_big)
ax_small.imshow(downsampled, cmap='turbo')

plt.tight_layout()
plt.show()

如果您不一定需要二次采样图像的轴来显示二次采样 width/height,而只是与您的 zoom/translation 匹配的区域(我不完全确定来自你的问题),你可以在 ax_small.imshow() 调用中使用 extent 参数。这指定了轴 space 中将显示图像的有效矩形。默认情况下,这只是图像的像素大小,但您可以将大小设置为等于完整采样图像的大小。

查看 documentation for imshow 了解更多信息。

...

# I want something like this:
ax_small = plt.subplot2grid((1, 2), (0, 1), sharex=ax_big, sharey=ax_big)
ax_small.imshow(downsampled, cmap='turbo', extent=[0, w, 0, h])

...

我在下面附上了一张结果图片。如您所见,二次采样图像基本上被拉伸到更大的区域。