2011-10-05 108 views
14

我有几个(27)用二维数组表示的图像,我用imshow()查看。我需要放大每个图像中完全相同的点。我知道我可以手动缩放,但这很乏味而且不够精确。有没有办法以编程方式指定图像的特定部分来显示而不是整个东西?Matplotlib imshow缩放功能?

回答

11

你可以使用plt.xlimplt.ylim设置区域被画在:

import matplotlib.pyplot as plt 
import numpy as np 

data=np.arange(9).reshape((3,3)) 
plt.imshow(data) 
plt.xlim(0.5, 1.5) 
plt.ylim(0.5,1.5) 
plt.show() 
+0

谢谢!我意识到我也可以裁剪数组的预显示,但是您的方法会保留数组的其余部分。 – Andruf

+0

在精彩的介绍* [Python科学入门](http://scipy-lectures.github.io/)*中,它位于matplotlib部分* [1.4。 Matplotlib:绘图,1.4.2.4。设置限制](http://scipy-lectures.github.io/intro/matplotlib/matplotlib.html#setting-limits)*。 –

3

如果你不需要你的图像的其余部分,你可以定义你想要的坐标裁剪图像的功能然后显示裁剪的图像。注意:这里'x'和'y'是视觉x和y(分别为图像上的水平轴和垂直轴),这意味着它与实际的x(行)和y(列)的NumPy阵列。

import scipy as sp 
import numpy as np 
import matplotlib.pyplot as plt 

def crop(image, x1, x2, y1, y2): 
    """ 
    Return the cropped image at the x1, x2, y1, y2 coordinates 
    """ 
    if x2 == -1: 
     x2=image.shape[1]-1 
    if y2 == -1: 
     y2=image.shape[0]-1 

    mask = np.zeros(image.shape) 
    mask[y1:y2+1, x1:x2+1]=1 
    m = mask>0 

    return image[m].reshape((y2+1-y1, x2+1-x1)) 

image = sp.lena() 
image_cropped = crop(image, 240, 290, 255, 272) 

fig = plt.figure() 
ax1 = fig.add_subplot(121) 
ax2 = fig.add_subplot(122) 

ax1.imshow(image) 
ax2.imshow(image_cropped) 

plt.show()