Python 为什么 plt.imshow() 不显示图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42812230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:10:21  来源:igfitidea点击:

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

pythonmatplotlibkeras

提问by Yu Gu

I am a newbie to keras, and when I tried to run my first keras program on my linux, something just didn't go as I wish. Here is my python code:

我是 keras 的新手,当我尝试在我的 linux 上运行我的第一个 keras 程序时,有些事情并没有如我所愿。这是我的python代码:

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])

The last sentence doesn't display anything. I copied those codes from a tutorial with out any modification. And there is nothing wrong with the backend of matplotlib on my computer. I have tested that through the code below.

最后一句没有显示任何内容。我从教程中复制了这些代码,没有做任何修改。而且我电脑上matplotlib的后端没有任何问题。我已经通过下面的代码测试过了。

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 then I got a image like that: enter image description here

然后我得到了这样的图像: 在此处输入图片说明


Moreover, I can get X_train[0] printed and it seems nothing wrong.
So what could be the reason for that? Why the imshow() function in my first code didn't display anything?


此外,我可以打印 X_train[0] 并且似乎没有错。
那么这可能是什么原因呢?为什么我的第一个代码中的 imshow() 函数没有显示任何内容?

回答by Marcin Mo?ejko

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

解决方案就像plt.show()在代码片段的末尾添加一样简单:

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()

回答by adaxi

plt.imshowjust finishes drawing a picture instead of printing it. If you want to print the picture, you just need to add plt.show.

plt.imshow只是完成绘制图片而不是打印它。如果要打印图片,只需添加plt.show.

回答by prosti

plt.imshowdisplays the image on the axes, but if you need to display multiple images you use show()to finish the figure. The next example shows two figures:

plt.imshow在轴上显示图像,但如果您需要显示多个图像,则可以show()用来完成图形。下一个示例显示了两个图:

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()

In Google Colab, if you comment out the show()method from previous example just a single image will display (the later one connected with X_train[1]).

在 Google Colab 中,如果您注释掉show()前面示例中的方法,则只会显示一个图像(后面的一个与 连接X_train[1])。

Here is the content from the help:

以下是帮助中的内容:

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).

回答by Rajat

If you want to print the picture using imshow() you also execute plt.show()

如果要使用 imshow() 打印图片,还需要执行 plt.show()