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 is tedious and not precise enough. Is there a way to programmatically specify a specific section of the image to show instead of the entire thing?
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()
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With