在不改变轴的情况下缩放matplotlib中的图像

时间:2013-05-24 19:13:32

标签: python matplotlib

我有一个显示情节的GUI。我想将该情节与现有图像相匹配。我使用以下方式在图表下显示图像:

myaxe.plot(...)
myaxeimage = myaxe.imshow(myimage, axpect='auto', extent=myaxe.axis(), zorder=-1)

我已经能够使用

播放图像的不透明度
myaxeimage.set_alpha()

现在我希望能够放大和缩小图像并使用GUI移动,而不会触及现有的绘图和轴,以便将其与我的绘图对齐。换句话说,我想缩放到给定的sxsy因子,并将图像的原点放在给定的(x,y)点,剪切图像的部分到轴外。我怎么能这样做?

2 个答案:

答案 0 :(得分:7)

有一个watermark example与matplotlib一起分发,有点类似。从该代码开始,我们可以修改如下:

首先使用ax.imshow绘制图像。我这样做是因为extent参数会影响ax的最终范围。由于我们希望最终范围由plt.plot(...)控制,让我们把它放在最后。

myaximage = ax.imshow(im, aspect='auto', extent=(1,15,0.3,0.7), alpha=0.5, origin='upper', zorder=-1)

使用extent=myaxe.axis()来控制图像的位置和大小,而不是extentextent=(1,15,0.3,0.7)将图片放在矩形中,左下角为(1, 0.3),右上角为(15, 0.7)

使用origin='upper',数组[0,0]的{​​{1}}索引位于范围的左上角。使用im时,它会放在左下角。


origin='lower'

enter image description here


如果您想展开图片并将其剪裁到图表的范围,您可能还需要使用import numpy as np import matplotlib.pyplot as plt import matplotlib.cbook as cbook import matplotlib.image as image np.random.seed(1) datafile = cbook.get_sample_data('logo2.png', asfileobj=False) im = image.imread(datafile) fig, ax= plt.subplots() myaximage = ax.imshow(im, aspect='auto', extent=(1,15,0.3,0.7), alpha=0.5, zorder=-1) ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=1.0, mfc='orange') ax.grid() plt.show() ax.set_xlim

ax.set_ylim

enter image description here


或者,为了获得更多控制,您可以使用myaximage = ax.imshow(im, aspect='auto', extent=(-1,25,0.3,0.7), alpha=0.5, zorder=-1, origin='upper') ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=1.0, mfc='orange') ax.set_xlim(0,20) ax.set_ylim(0,1) 将图像剪辑为任意路径:

myaximage.set_clip_path

enter image description here

答案 1 :(得分:0)

最后,我遵循了tcaswell建议并使用了2个不同的轴。这样,我只需要使用图像轴的set_xlim()set_ylim()来更改图像的原点和/或缩放系数。为了得到我的情节下面的图像,没有用图的框架隐藏它,我删除了绘图的框架并使用了图像轴的框架。我还隐藏了图像轴的刻度。

from matplotlib import pyplot

f = pyplot.figure()
a = f.add_subplot(111, frameon=False) # Remove frame
a.plot(...)

myimg = pyplot.imread(...)
imgaxes = f.add_axes(a.get_position(), # new axes with same position
    label='image', # label to ensure imgaxes is different from a
    zorder=-1, # put image below the plot
    xticks=[], yticks=[]) # remove the ticks
img = imgaxes.imshow(myimg, aspect='auto') # ensure image takes all the place

# now, to modify things
img.set_alpha(...)
imgaxes.set_xlim((x1, x2)) # x1 and x2 must be calculated from
                           # image size, origin, and zoom factor