3D RGB Numpy数组到图像文件导致TypeE

2024-07-04 07:50:37 发布

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

from PIL import Image

array = np.zeros((3,64,64),'uint8')
array[0] = redToImage;
array[1] = blueToImage;
array[2] = greenToImage;

img = Image.fromarray(array)
if img.mode != 'RGB':
   img = img.convert('RGB')
img.save('testrgb.jpg')

我有redToImageblueToImagegreenToImage,它们都是(64,64)大小的numpy数组。 但是,当我尝试从数组创建图像时,它给了我这个错误。我真的找了又试 很多方法

它给出了以下错误:

***---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\Anaconda3\lib\site-packages\PIL\Image.py in fromarray(obj, mode)
   2514             typekey = (1, 1) + shape[2:], arr['typestr']
-> 2515             mode, rawmode = _fromarray_typemap[typekey]
   2516         except KeyError:
KeyError: ((1, 1, 64), '|u1')
During handling of the above exception, another exception occurred:
TypeError                                 Traceback (most recent call last)
<ipython-input-331-9ce9e6816b75> in <module>
      6 array[2] = greenToImage;
      7
----> 8 img = Image.fromarray(array)
      9 if img.mode != 'RGB':
     10     img = img.convert('RGB')
~\Anaconda3\lib\site-packages\PIL\Image.py in fromarray(obj, mode)
   2515             mode, rawmode = _fromarray_typemap[typekey]
   2516         except KeyError:
-> 2517             raise TypeError("Cannot handle this data type")
   2518     else:
   2519         rawmode = mode
TypeError: Cannot handle this data type***

Tags: inimageimgpilmodergbarraykeyerror
1条回答
网友
1楼 · 发布于 2024-07-04 07:50:37

键入错误表示Image.fromarray(array)无法自动将(3,64,64)矩阵重塑为(64,64,3)矩阵fromarray(x)期望x将包含3层或64x64块,而不是64层的3x64块。将代码更改为类似于下面的内容会产生所需的结果(在我的示例中是一个绿色的64x64像素.jpg图像)

from PIL import Image
import numpy as np

array = np.zeros((64, 64, 3), 'uint8')

'''
Creating dummy versions of redToImage, greenToImage and blueToImage.
In this example, their combination denotes a completely green 64x64 pixels square.
'''
array[:, :, 0] = np.zeros((64, 64))
array[:, :, 1] = np.ones((64, 64))
array[:, :, 2] = np.zeros((64, 64))

img = Image.fromarray(array)
if img.mode != 'RGB':
    img = img.convert('RGB')
img.save('testrgb.jpg')

相关问题 更多 >

    热门问题