问题描述
在很多情况下,我们都需要使用matplotlib里面的imshow函数来显示图像,如果使用的是jupyter notbook直接输入matplotlib.pyplot.imshow()来显示是没有任何问题的。但是在IDE中()比如pycharm就会出现闪退或者无法显示的情况。
解决方法
原因是有些书籍中确实只把代码给到imshow这一行,但是其实因为notebook过于强大,可以在缺少某些代码的情况下正常显示(我猜的)。而正常的python代码中应该在最后面加入显示的show()函数,我的理解是imshow()只是对需要现实的的图片进行参数定义(比如大小,颜色,xy轴信息),而show()才是最终打印的函数。
广泛流行的方法就是 在matplotlib.pyplot.imshow(…)
的后面再加上一行matplotlib.pyplot.show(注意括号里为空)
下面给出官方的reference和一个demo,大家可以参考进行规范编程
官方reference
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imshow.html#matplotlib-pyplot-imshow
matplotlib.pyplot.imshow
matplotlib.pyplot.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=, filternorm=1, filterrad=4.0, imlim=, resample=None, url=None, *, data=None, **kwargs)[source]
Display an image, i.e. data on a 2D regular raster.
官方demo
Barcode Demo
This demo shows how to produce a one-dimensional image, or “bar code”.
import matplotlib.pyplot as plt
import numpy as np
#Fixing random state for reproducibility
np.random.seed(19680801)
#the bar
x = np.random.rand(500) > 0.7
barprops = dict(aspect='auto', cmap='binary', interpolation='nearest')
fig = plt.figure()
#a vertical barcode
ax1 = fig.add_axes([0.1, 0.1, 0.1, 0.8])
ax1.set_axis_off()
ax1.imshow(x.reshape((-1, 1)), **barprops)
#a horizontal barcode
ax2 = fig.add_axes([0.3, 0.4, 0.6, 0.2])
ax2.set_axis_off()
ax2.imshow(x.reshape((1, -1)), **barprops)
plt.show()