Python “如何修复”;类型错误:图像数据的维度无效;使用matplotlib查看图像时出错

Python “如何修复”;类型错误:图像数据的维度无效;使用matplotlib查看图像时出错,python,matplotlib,Python,Matplotlib,我正在尝试将图像转换为灰度,并使用pyplot显示它。我正在采取的步骤是: 步骤1:在python中使用Pillow读取图像作为输入 步骤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=n

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

步骤1:在python中使用Pillow读取图像作为输入

步骤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.数组的形状

(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
TypeError回溯(最近一次调用)
在里面
1 img=np.数组(img)
2个打印(图像形状)
---->3 plt.imshow(img)
imshow中的~/.local/lib/python3.6/site-packages/matplotlib/pyplot.py(X,cmap,norm,aspect,interpolation,alpha,vmin,vmax,origin,extent,shape,filternorm,filterrad,imlim,重采样,url,data,**kwargs)
2697 filternorm=filternorm,filterrad=filterrad,imlim=imlim,
2698重采样=重采样,url=url,**({“数据”:数据}如果数据不是
->2699无其他{},**kwargs)
2700 sci
2701返回
内部文件中的~/.local/lib/python3.6/site packages/matplotlib/_init__u;.py(ax,数据,*args,**kwargs)
1808“Matplotlib列表!)”%(标签名称,函数名称),
1809运行时警告,堆栈级别=2)
->1810返回函数(ax,*args,**kwargs)
1811
1812内部.\uuuuu文档\uuuuu=\u添加数据\uu文档(内部.\uuuuu文档\uuuuuuuuuu),
imshow中的~/.local/lib/python3.6/site-packages/matplotlib/axes//u axes.py(self、X、cmap、norm、aspect、interpolation、alpha、vmin、vmax、origin、extent、shape、filternorm、filterrad、imlim、重采样、url、**kwargs)
5492重采样=重采样,**kwargs)
5493
->5494 im.set_数据(X)
5495 im.set_α(α)
5496如果im.get\u clip\u path()为无:
集合数据中的~/.local/lib/python3.6/site-packages/matplotlib/image.py(self,A)
636如果不是(自身.\u A.ndim==2
637或self.\A.ndim==3和self.\A.shape[-1]在[3,4]中:
-->638 raise TypeError(“图像数据的尺寸无效”)
639
640如果self.\u A.ndim==3:
TypeError:图像数据的维度无效
这是我试图读取的图像,并将其转换为灰度

您不必将图像保存为
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。如果需要,请确保为其指定不同的名称


另外,如果您想显示图像,请不要忘记将
plt.show()
放在末尾。

我仍然收到相同的错误message@SanjayMoharana试试新鲜的,它可以工作。@Amazingthingsaroundyour它不工作。它仍然抛出相同的错误消息。@SanjayMoharana你能在你的问题中发布完整的错误回溯吗?@SanjayMoharana看着错误回溯,你没有尝试我的答案,因为你仍然将图像存储为
np.array
。使用
.convert('L'))
如副本所示。(因为jpg图像没有alpha通道)