Invalid dimension for image data in plt.imshow() Invalid dimension for image data in plt.imshow() python-3.x python-3.x

Invalid dimension for image data in plt.imshow()


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 pltimg_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")


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


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