原文链接:http://www.juzicode.com/archives/3502
错误提示:
matplotlib的imshow()方法显示图像时提示:TypeError: Invalid shape (100, 100, 5) for image data
#juzicode.com; #vx:桔子code
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
arr = np.full((100,100,3),100)
plt.imshow(arr)
arr = np.full((100,100,5),100)
plt.imshow(arr)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-11-9ef92a2fb8cf> in <module>
8
9 arr = np.full((100,100,5),100)
---> 10 plt.imshow(arr)
d:\python\python38\lib\site-packages\matplotlib\pyplot.py in imshow(X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, filternorm, filterrad, resample, url, data, **kwargs)
2722 filternorm=True, filterrad=4.0, resample=None, url=None,
2723 data=None, **kwargs):
-> 2724 __ret = gca().imshow(
2725 X, cmap=cmap, norm=norm, aspect=aspect,
2726 interpolation=interpolation, alpha=alpha, vmin=vmin,
d:\python\python38\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
1445 def inner(ax, *args, data=None, **kwargs):
1446 if data is None:
-> 1447 return func(ax, *map(sanitize_sequence, args), **kwargs)
1448
1449 bound = new_sig.bind(ax, *args, **kwargs)
d:\python\python38\lib\site-packages\matplotlib\axes\_axes.py in imshow(self, X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, filternorm, filterrad, resample, url, **kwargs)
5521 resample=resample, **kwargs)
5522
-> 5523 im.set_data(X)
5524 im.set_alpha(alpha)
5525 if im.get_clip_path() is None:
d:\python\python38\lib\site-packages\matplotlib\image.py in set_data(self, A)
709 if not (self._A.ndim == 2
710 or self._A.ndim == 3 and self._A.shape[-1] in [3, 4]):
--> 711 raise TypeError("Invalid shape {} for image data"
712 .format(self._A.shape))
713
TypeError: Invalid shape (100, 100, 5) for image data
错误原因:
1、imshow()方法显示numpy数组,数组要么是2维数组(灰度图),要么是3维数组(彩色图)。如果是3维数组,其第3维必须是3或者4,正好对应了3通道或者4通到彩色图像。错误信息中也有完整提示:
709 if not (self._A.ndim == 2
710 or self._A.ndim == 3 and self._A.shape[-1] in [3, 4]):
解决方法:
1、matploglib的imshow()方法如果显示3维数组,只能显示3通道或者4通道的彩色图像,其他通道数没有实际意义。
关注微信公众号:“桔子code”,欢迎后台留言撩我,我会尽我所能为你解惑Python,C等编程知识