Python 类型错误:使用 imshow() 绘制数组时图像数据的维度无效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36431496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:52:21  来源:igfitidea点击:

TypeError: Invalid dimensions for image data when plotting array with imshow()

pythonarraysnumpymatplotlib

提问by Essex

For the following code

对于以下代码

# Numerical operation
SN_map_final = (new_SN_map - mean_SN) / sigma_SN  

# Plot figure
fig12 = plt.figure(12)
fig_SN_final = plt.imshow(SN_map_final, interpolation='nearest')
plt.colorbar()

fig12 = plt.savefig(outname12)

with new_SN_mapbeing a 1D array and mean_SNand sigma_SNbeing constants, I get the following error.

new_SN_map作为一维数组,mean_SNsigma_SN为常数,我碰到下面的错误。

Traceback (most recent call last):
  File "c:\Users\Valentin\Desktop\Stage M2\density_map_simple.py", line 546, in <module>
    fig_SN_final = plt.imshow(SN_map_final, interpolation='nearest')
  File "c:\users\valentin\appdata\local\enthought\canopy\user\lib\site-packages\matplotlib\pyplot.py", line 3022, in imshow
    **kwargs)
  File "c:\users\valentin\appdata\local\enthought\canopy\user\lib\site-packages\matplotlib\__init__.py", line 1812, in inner
    return func(ax, *args, **kwargs)
  File "c:\users\valentin\appdata\local\enthought\canopy\user\lib\site-packages\matplotlib\axes\_axes.py", line 4947, in imshow
    im.set_data(X)
  File "c:\users\valentin\appdata\local\enthought\canopy\user\lib\site-packages\matplotlib\image.py", line 453, in set_data
    raise TypeError("Invalid dimensions for image data")
TypeError: Invalid dimensions for image data

What is the source of this error? I thought my numerical operations were allowed.

这个错误的根源是什么?我以为我的数值运算是允许的。

回答by MSeifert

There is a (somewhat) related question on StackOverflow:

StackOverflow 上有一个(有点)相关的问题:

Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeezed or sliced into a 2D array.

这里的问题是形状为 (nx,ny,1) 的数组仍被视为 3D 数组,并且必须是squeezed 或切片为 2D 数组。

More generally, the reason for the Exception

更一般地说,异常的原因

TypeError: Invalid dimensions for image data

类型错误:图像数据的尺寸无效

is shown here: matplotlib.pyplot.imshow()needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!

如下所示:matplotlib.pyplot.imshow()需要一个 2D 数组,或一个第三维形状为 3 或 4 的 3D 数组!

You can easily check this with (these checks are done by imshow, this function is only meant to give a more specific message in case it's not a valid input):

你可以很容易地检查这个(这些检查是由 完成的imshow,这个函数只是为了在它不是有效输入的情况下提供更具体的消息):

from __future__ import print_function
import numpy as np

def valid_imshow_data(data):
    data = np.asarray(data)
    if data.ndim == 2:
        return True
    elif data.ndim == 3:
        if 3 <= data.shape[2] <= 4:
            return True
        else:
            print('The "data" has 3 dimensions but the last dimension '
                  'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
                  ''.format(data.shape[2]))
            return False
    else:
        print('To visualize an image the data must be 2 dimensional or '
              '3 dimensional, not "{}".'
              ''.format(data.ndim))
        return False

In your case:

在你的情况下:

>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False

The np.asarrayis what is done internally by matplotlib.pyplot.imshowso it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list) it's necessary.

np.asarray是由内部完成的,matplotlib.pyplot.imshow因此通常最好您也这样做。如果您有一个 numpy 数组,它已过时,但如果没有(例如 a list),则它是必要的。



In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()

在您的特定情况下,您有一个一维数组,因此您需要添加一个维度 np.expand_dims()

import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0)  # or axis=1
plt.imshow(a)
plt.show()

enter image description here

在此处输入图片说明

or just use something that accepts 1D arrays like plot:

或者只是使用接受一维数组的东西,例如plot

a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()

enter image description here

在此处输入图片说明