如何显示一个npy文件中的许多图像?

时间:2019-05-21 15:35:19

标签: python python-3.x image matplotlib

我尝试显示一个文件npy中的图像,但始终失败。如何显示一个npy文件中的许多图像并将其保存?这是我的代码

import matplotlib.pyplot as plt 
import numpy as np

dataArray= np.load('chunks_64x64_NORMvsDISTRESS_train_chunk_000_x.npy')
#scaled = ((dataArray + 1)*255/2.).astype(np.uint8)
#print(dataArray)
print(dataArray)

plt.imshow(dataArray, cmap='gray')
plt.show()

我希望输出是图像,但是输出是

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-16-dbe8084de082> in <module>
----> 1 plt.imshow(dataArray, cmap='gray')
      2 plt.show()

~\Anaconda3\lib\site-packages\matplotlib\pyplot.py in imshow(X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, data, **kwargs)
   2697         filternorm=filternorm, filterrad=filterrad, imlim=imlim,
   2698         resample=resample, url=url, **({"data": data} if data is not
-> 2699         None else {}), **kwargs)
   2700     sci(__ret)
   2701     return __ret

~\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
   1808                         "the Matplotlib list!)" % (label_namer, func.__name__),
   1809                         RuntimeWarning, stacklevel=2)
-> 1810             return func(ax, *args, **kwargs)
   1811 
   1812         inner.__doc__ = _add_data_doc(inner.__doc__,

~\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in imshow(self, X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, **kwargs)
   5492                               resample=resample, **kwargs)
   5493 
-> 5494         im.set_data(X)
   5495         im.set_alpha(alpha)
   5496         if im.get_clip_path() is None:

~\Anaconda3\lib\site-packages\matplotlib\image.py in set_data(self, A)
    636         if not (self._A.ndim == 2
    637                 or self._A.ndim == 3 and self._A.shape[-1] in [3, 4]):
--> 638             raise TypeError("Invalid dimensions for image data")
    639 
    640         if self._A.ndim == 3:

TypeError: Invalid dimensions for image data

1 个答案:

答案 0 :(得分:0)

这可能是由于形状数组(nx,ny,1)仍被视为3D数组的问题所致。 测试形状并将其压缩或切成2D阵列。试试:

import numpy as np
np.squeeze(array, axis=2)