-1

I have numpy file stored as "test.npy" which is a 2 dimensional Synthetic Aperture Radar(SAR) image data with VV and VH polarization bands. How do I plot this 2 dimensional image array using matplotlib?

import numpy as np

img_array = np.load('test.npy')
from matplotlib import pyplot as plt

plt.imshow(img_array[1], cmap='gray')
plt.show()

But the line:

plt.imshow(img_array[0], cmap='gray')

plots only the first band in the list. So, how is it possible for me to plot 2 dimensional image array?

4
  • have you tried plt.imshow(img_array)? You can pass the 2-d numpy array directly in to imshow() Commented Aug 16, 2021 at 13:36
  • yeah I tried that and got an error like this one: "TypeError: Invalid shape (2, 512, 512) for image data " Commented Aug 16, 2021 at 13:52
  • Also, "print(img_array.shape)" returns the shape of image array as: (2, 512, 512) while "print(img_array[0].shape" returns the shape of the image array as: (512, 512). Does this have to do anything with the original shape of my img_array as (2, 512, 512). Commented Aug 16, 2021 at 13:58
  • Please include a minimal reproducible example of the data as formatted text Commented Aug 16, 2021 at 16:02

2 Answers 2

0

The problem is that your array has the shape (2, 512, 512) but matplotlib can only show grayscale, rgb or rgba images. Also the array needs to have the form (H,W), (H,W,3) or (H,W,4) respectively as you can see in the documentation here. Therefore I suggest you swap the axes and extend the array to a (H,W,3) shape with an additionally empty channel:

import numpy as np
from matplotlib import pyplot as plt

img_array = np.load('test.npy')
c, h, w = img_array.shape
img = np.zeros((h, w, 3))  # create image of zeros with (height, width, channel)
img[:, :, :2] = img_array.swapaxes(0,2) # fill the first 2 channels
plt.imshow(img)
plt.show()
Sign up to request clarification or add additional context in comments.

1 Comment

I still get this error: TypeError: Invalid shape (512, 512, 2) for image data
0
import numpy as np
from matplotlib import pyplot as plt

img2d = np.load('test.npy')
img3d = np.concatenate(( np.expand_dims(img2d[0],-1), np.expand_dims(img2d[1],-1),np.expand_dims((img2d[0]+img2d[1])/2, -1)), -1)


plt.imshow(img3d)
plt.show()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.