由于数组形状,将 NumPy RGB 数组保存为图像失败

Saving NumPy RGB array as an image fails because of the array shape

我有一堆从屏幕缓冲区获得的形状为 (3, 225, 400) 的帧数组。由于形状的原因,我在将它们保存为 RGB png 图像时遇到了问题。

> arr = np.load("frame134.npy") 
> print(arr)

[[[63 47 63 ... 47 47 27]
  [63 47 39 ... 47 55 35]
  [63 47 39 ... 55 55 47]
  ...
  [91 35 35 ... 79 79 79]
  [91 35 63 ... 79 79 79]
  [55 63 63 ... 79 79 79]]

 [[71 47 47 ... 55 55 27]
  [71 47 39 ... 55 63 43]
  [71 47 39 ... 63 63 55]
  ...
  [99 35 35 ... 79 79 79]
  [99 35 71 ... 79 79 79]
  [63 71 71 ... 79 79 79]]

 [[43 47 23 ... 31 31 27]
  [43 47 39 ... 31 39 15]
  [43 47 39 ... 39 39 31]
  ...
  [71 35 35 ... 79 79 79]
  [71 35 43 ... 79 79 79]
  [39 43 43 ... 79 79 79]]]

当我尝试使用 PIL 保存它时:

im = Image.fromarray(arr, "RGB")
im.save("tmp.png")

结果如下:

或者,如果我使用 matplotlib:

> plt.imsave('tmp.png', arr)
ValueError: Third dimension must be 3 or 4

如何调整数组的大小以使其能够正确保存?谢谢!

您必须将第一个轴移动到第三个轴。 这可以通过

来完成
arr = np.moveaxis(arr , 0, -1)