Python PIL/枕头将图像转换为列表并再次转换

Python PIL/枕头将图像转换为列表并再次转换,python,python-3.x,numpy,python-imaging-library,pillow,Python,Python 3.x,Numpy,Python Imaging Library,Pillow,我试图打开一张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.

我试图打开一张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()

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

img2.putdata(img_ints.astype(int).flatten())
要获得更有效的加载图像的方法,请查看

但是使用
image.tobytes()
(枕头)代替
image.tostring()
(PIL)。