TypeError:使用imshow()打印数组时,图像数据的维度无效

2024-04-25 08:10:09 发布

您现在位置:Python中文网/ 问答频道 /正文

对于以下代码

# 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)

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

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


Tags: inpymaplocallinepltusersappdata
1条回答
网友
1楼 · 发布于 2024-04-25 08:10:09

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

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

一般来说,例外的原因

TypeError: Invalid dimensions for image data

如图所示:^{}需要二维数组,或者三维数组的形状为3或4!

您可以使用(这些检查由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

就你而言:

>>> 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

np.asarray是由matplotlib.pyplot.imshow在内部完成的,所以通常最好也这样做。如果你有一个numpy数组,它是过时的,但如果不是(例如list),它是必要的。


在您的特定情况下,您有一个1D数组,因此需要添加一个带^{}的维度

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

或者只使用接受1D数组的东西,比如plot

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

enter image description here

相关问题 更多 >