如何将 numpy 数组中的图像读入 PIL 图像?
How to read image from numpy array into PIL Image?
我正在尝试通过执行以下操作使用 PIL 从 numpy 数组中读取图像:
from PIL import Image
import numpy as np
#img is a np array with shape (3,256,256)
Image.fromarray(img)
并且出现以下错误:
File "...Image.py", line 2155, in fromarray
raise TypeError("Cannot handle this data type")
我认为这是因为 fromarray
期望形状为 (height, width, num_channels)
但是我拥有的数组的形状为 (num_channels, height, width)
因为它存储在 lmdb
数据库。
如何重塑图像以使其与 Image.fromarray
兼容?
尝试
img = np.reshape(256, 256, 3)
Image.fromarray(img)
你不需要重塑。 This is what rollaxis is for:
Image.fromarray(np.rollaxis(img, 0,3))
将 numpy 数组的数据类型定义为 np.uint8
为我修复了它。
>>> img = np.full((256, 256), 3)
>>> Image.fromarray(img)
...
line 2753, in fromarray
raise TypeError("Cannot handle this data type: %s, %s" % typekey) from e
TypeError: Cannot handle this data type: (1, 1), <i8
所以用正确的数据类型定义数组:
>>> img = np.full((256, 256), 3, dtype=np.uint8)
>>> Image.fromarray(img)
<PIL.Image.Image image mode=L size=256x256 at 0x7F346EA31130>
成功创建Image对象
或者您可以简单地修改现有的 numpy 数组:
img = img.astype(np.uint8)
我正在尝试通过执行以下操作使用 PIL 从 numpy 数组中读取图像:
from PIL import Image
import numpy as np
#img is a np array with shape (3,256,256)
Image.fromarray(img)
并且出现以下错误:
File "...Image.py", line 2155, in fromarray
raise TypeError("Cannot handle this data type")
我认为这是因为 fromarray
期望形状为 (height, width, num_channels)
但是我拥有的数组的形状为 (num_channels, height, width)
因为它存储在 lmdb
数据库。
如何重塑图像以使其与 Image.fromarray
兼容?
尝试
img = np.reshape(256, 256, 3)
Image.fromarray(img)
你不需要重塑。 This is what rollaxis is for:
Image.fromarray(np.rollaxis(img, 0,3))
将 numpy 数组的数据类型定义为 np.uint8
为我修复了它。
>>> img = np.full((256, 256), 3)
>>> Image.fromarray(img)
...
line 2753, in fromarray
raise TypeError("Cannot handle this data type: %s, %s" % typekey) from e
TypeError: Cannot handle this data type: (1, 1), <i8
所以用正确的数据类型定义数组:
>>> img = np.full((256, 256), 3, dtype=np.uint8)
>>> Image.fromarray(img)
<PIL.Image.Image image mode=L size=256x256 at 0x7F346EA31130>
成功创建Image对象
或者您可以简单地修改现有的 numpy 数组:
img = img.astype(np.uint8)