使用matplotlib查看图像时如何解决“类型错误:图像数据的尺寸无效”错误

时间:2019-06-11 06:11:59

标签: python matplotlib

我正在尝试将图像转换为灰度并使用pyplot进行显示。我正在采取的步骤是:

第1步:使用python中的枕头读取图像作为输入

第2步:使用.convert('LA')

将其转换为灰度图像

这是代码:

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

img = Image.open('28.jpg').convert('LA')
img.save('greyscale.png')

img=np.array(img)
print (img.shape)
plt.imshow(img)

将其输出为np.array的形状:

(360, 480, 2)

问题是,当我尝试使用matplotlib.pyplot查看此灰度图像的输出时,会引发以下错误错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-4-f6fac0acd82f> in <module>
      1 img = np.array(img)
      2 print (img.shape)
----> 3 plt.imshow(img)

~/.local/lib/python3.6/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

~/.local/lib/python3.6/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__,

~/.local/lib/python3.6/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:

~/.local/lib/python3.6/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

这是我正在尝试读取并将其转换为灰度的图像 28.jpg

1 个答案:

答案 0 :(得分:0)

您不必将图像另存为np.array,只需将转换后的图像直接提供给plt.imshow()。像这样:

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

img = Image.open('28.jpg').convert('LA')
img.save('greyscale.png')

plt.imshow(img)

您仍然可以将图像存储为所需的np.array,只需确保使用其他名称即可。

此外,如果要显示图像,请不要忘记将plt.show()放在最后。