6

I am using mnist dataset for training a capsule network in keras background. After training, I want to display an image from mnist dataset. For loading images, mnist.load_data() is used. The data is stored as (x_train, y_train),(x_test, y_test). Now, for visualizing image, my code is as follows:

img_path = x_test[1]  
print(img_path.shape)
plt.imshow(img_path)
plt.show()

The code gives output as follows:

(28, 28, 1)

and the error on plt.imshow(img_path) as follows:

TypeError: Invalid dimensions for image data

How to show image in png format. Help!

codeslord
  • 2,172
  • 14
  • 20
Anusha Mehta
  • 99
  • 1
  • 1
  • 10

4 Answers4

7

As per the comment of @sdcbr using np.sqeeze reduces unnecessary dimension. If image is 2 dimensions then imshow function works fine. If image has 3 dimensions then you have to reduce extra 1 dimension. But, for higher dim data you will have to reduce it to 2 dims, so np.sqeeze may be applied multiple times. (Or you may use some other dim reduction functions for higher dim data)

import numpy as np  
import matplotlib.pyplot as plt
img_path = x_test[1]  
print(img_path.shape)
if(len(img_path.shape) == 3):
    plt.imshow(np.squeeze(img_path))
elif(len(img_path.shape) == 2):
    plt.imshow(img_path)
else:
    print("Higher dimensional data")
shantanu pathak
  • 2,018
  • 19
  • 26
3

Example:

plt.imshow(test_images[0])

TypeError: Invalid shape (28, 28, 1) for image data

Correction:

plt.imshow((tf.squeeze(test_images[0])))

Number 7

Simas Joneliunas
  • 2,890
  • 20
  • 28
  • 35
Deepak
  • 31
  • 1
2

You can use tf.squeeze for removing dimensions of size 1 from the shape of a tensor.

plt.imshow( tf.shape( tf.squeeze(x_train) ) )

Check out TF2.0 example

Parth Patel
  • 68
  • 1
  • 9
0

matplotlib.pyplot.imshow() does not support images of shape (h, w, 1). Just remove the last dimension of the image by reshaping the image to (h, w): newimage = reshape(img,(h,w)).

jeffhale
  • 3,759
  • 7
  • 40
  • 56