Search code examples
pythonmatplotlibkeras

Why doesn't plt.imshow() display the image?


I have this code, copied from a tutorial:

import numpy as np
np.random.seed(123)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test) = mnist.load_data()
print X_train.shape
from matplotlib import pyplot as plt
plt.imshow(X_train[0])

No image was displayed. Why not?

There doesn't appear to be anything wrong with the backend of matplotlib on my computer. I tested that like so:

import matplotlib.pyplot as plt

data = [[0, 0.25], [0.5, 0.75]]

fig, ax = plt.subplots()
im = ax.imshow(data, cmap=plt.get_cmap('hot'), interpolation='nearest',
               vmin=0, vmax=1)
fig.colorbar(im)
plt.show()

and was able to produce an image: enter image description here

I also tried printing X_train[0] and it looks right.


Solution

  • The solution was as simple as adding plt.show() at the end of the code snippet:

    import numpy as np
    np.random.seed(123)
    from keras.models import Sequential
    from keras.layers import Dense, Dropout, Activation, Flatten
    from keras.layers import Convolution2D, MaxPooling2D
    from keras.utils import np_utils
    from keras.datasets import mnist
    (X_train,y_train),(X_test,y_test) = mnist.load_data()
    print X_train.shape
    from matplotlib import pyplot as plt
    plt.imshow(X_train[0])
    plt.show()