PIL/Pillow 将图像转换为列表并再次返回

PIL/Pillow convert Image to list and back again

我正在尝试打开 RGB 图片,将其转换为灰度,然后将其表示为从 0 到 1 缩放的浮点列表。最后,我想将其再次转换回图像。但是,在下面的代码中,我的转换过程中的某些部分失败了,因为 img.show()(原始图像)显示正确,而 img2.show() 显示全黑图片。我错过了什么?

import numpy as np
from PIL import Image

ocr_img_path = "./ocr-test.jpg"

# Open image, convert to grayscale
img = Image.open(ocr_img_path).convert("L")

# Convert to list
img_data = img.getdata()
img_as_list = np.asarray(img_data, dtype=float) / 255
img_as_list = img_as_list.reshape(img.size)

# Convert back to image
img_mul = img_as_list * 255
img_ints = np.rint(img_mul)
img2 = Image.new("L", img_as_list.shape)
img2.putdata(img_ints.astype(int))

img.show()
img2.show()

The image used

解决方法是在将数组放入图像之前将其展平。我认为 PIL 将多维数组解释为不同的色带。

img2.putdata(img_ints.astype(int).flatten())

有关更有效的加载图像的方法,请查看

https://blog.eduardovalle.com/2015/08/25/input-images-theano/

但使用 image.tobytes() (Pillow) 而不是 image.tostring() (PIL)。 .