如何将numpy数组中的图像读入PIL图像?

Aly*_*Aly 7 python numpy pillow lmdb

我正在尝试使用PIL从numpy数组中读取图像,执行以下操作:

from PIL import Image
import numpy as np
#img is a np array with shape (3,256,256)
Image.fromarray(img)
Run Code Online (Sandbox Code Playgroud)

并收到以下错误:

File "...Image.py", line 2155, in fromarray
    raise TypeError("Cannot handle this data type")
Run Code Online (Sandbox Code Playgroud)

我认为这是因为fromarray期望形状是(height, width, num_channels)我拥有的数组,(num_channels, height, width)因为它存储在lmdb数据库中.

如何重塑图像以使其兼容Image.fromarray

Lan*_*ing 10

你不需要重塑.这是rollaxis的用途:

Image.fromarray(np.rollaxis(img, 0,3))
Run Code Online (Sandbox Code Playgroud)


Rya*_*yan 5

尝试

img = np.reshape(256, 256, 3)
Image.fromarray(img)
Run Code Online (Sandbox Code Playgroud)