Skip to content Skip to sidebar Skip to footer

Matplotlib Imshow Zoom Function?

I have several (27) images represented in 2D arrays that I am viewing with imshow(). I need to zoom in on the exact same spot in every image. I know I can manually zoom, but this i

Solution 1:

You could use plt.xlim and plt.ylim to set the region to be plotted:

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()

Solution 2:

If you do not need the rest of your image, you can define a function that crop the image at the coordinates you want and then display the cropped image.

Note: here 'x' and 'y' are the visual x and y (horizontal axis and vertical axis on the image, respectively), meaning that it is inverted compared to the real x (row) and y (column) of the NumPy array.

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

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

    mask = np.zeros(image.shape)
    mask[y1:y2+1, x1:x2+1]=1
    m = mask>0return 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()

Post a Comment for "Matplotlib Imshow Zoom Function?"