yu-gu
Tengo este código, copiado de un 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 se mostró ninguna imagen. ¿Por qué no?
No parece haber ningún problema con el backend de matplotlib
en mi computadora. Lo probé así:
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()
y fue capaz de producir una imagen:
También intenté imprimir X_train[0]
y se ve bien.
La solución fue tan simple como agregar plt.show()
al final del fragmento de código:
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()
-
Esto solo evita responder POR QUÉ mientras obtienes 168 votos a favor… Extraño
– Kuo
26 de noviembre de 2020 a las 11:39
-
Marzo 2021. Sigue faltando lo mismo en el tutorial tensorflow.org/tutorials/images/transfer_learning
– piso
24 de marzo de 2021 a las 12:04
-
@Kuo El código original no dibuja la imagen porque no contiene la línea de código que se agregó. Simple. El título, por supuesto, implica una expectativa de que
.imshow
sí mismo haría esto; pero la única manera de responder “¿por qué no llama.imshow
dibujar la imagen?” literalmente es “porque no está definido para hacer algo así”. La pregunta de seguimiento natural es “bueno, ¿por qué lo llamanimshow
si no muestra una imagen?”, pero eso está fuera de tema para Stack Overflow; no vamos a especular sobre el proceso de pensamiento de los autores de matplotlib.– Karl Knechtel
10 de enero a las 2:22
adaxi
plt.imshow
simplemente termina de dibujar una imagen en lugar de imprimirla. Si desea imprimir la imagen, solo necesita agregar plt.show
.
-
Desde ese punto de vista, sería mejor y menos confuso cambiar el nombre de “imshow” a “imdraw”. ¿No estás de acuerdo?
– Aram Paronikyan
1 de agosto de 2019 a las 13:55
-
@AramParonikyan matplotlib es capas sobre capas de confusión y diseño infernal. Un día, la gente se mudará a una mejor biblioteca (cv2 es aún más confuso)
– qwr
22 de abril de 2022 a las 3:58
prosti
plt.imshow
muestra la imagen en los ejes, pero si necesita mostrar varias imágenes, use show()
para terminar la figura. El siguiente ejemplo muestra dos figuras:
import numpy as np
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test) = mnist.load_data()
from matplotlib import pyplot as plt
plt.imshow(X_train[0])
plt.show()
plt.imshow(X_train[1])
plt.show()
En Google Colab, si comentas el show()
método del ejemplo anterior, solo se mostrará una sola imagen (la última conectada con X_train[1]
).
Aquí está el contenido de la ayuda:
plt.show(*args, **kw)
Display a figure.
When running in ipython with its pylab mode, display all
figures and return to the ipython prompt.
In non-interactive mode, display all figures and block until
the figures have been closed; in interactive mode it has no
effect unless figures were created prior to a change from
non-interactive to interactive mode (not recommended). In
that case it displays the figures but does not block.
A single experimental keyword argument, *block*, may be
set to True or False to override the blocking behavior
described above.
plt.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=None, filternorm=1, filterrad=4.0, imlim=None, resample=None, url=None, hold=None, data=None, **kwargs)
Display an image on the axes.
Parameters
----------
X : array_like, shape (n, m) or (n, m, 3) or (n, m, 4)
Display the image in `X` to current axes. `X` may be an
array or a PIL image. If `X` is an array, it
can have the following shapes and types:
- MxN -- values to be mapped (float or int)
- MxNx3 -- RGB (float or uint8)
- MxNx4 -- RGBA (float or uint8)
The value for each component of MxNx3 and MxNx4 float arrays
should be in the range 0.0 to 1.0. MxN arrays are mapped
to colors based on the `norm` (mapping scalar to scalar)
and the `cmap` (mapping the normed scalar to a color).
Intenta agregar
plt.show()
al final de su fragmento de código.– Marcin Możejko
15 de marzo de 2017 a las 14:21
Este problema suele surgir cuando copia código de Jupyter
– arame3333
16 de julio de 2020 a las 9:37