[英]PIL/Pillow convert Image to list and back again
I'm trying to open an RGB picture, convert it to grayscale, then represent it as a list of floats scaled from 0 to 1. At last, I want to convert it back again to an Image.我正在尝试打开 RGB 图片,将其转换为灰度,然后将其表示为从 0 到 1 缩放的浮点数列表。最后,我想将其再次转换回图像。 However, in the code below, something in my conversion procedure fails, as
img.show()
(the original image) displays correctly while img2.show()
display an all black picture.但是,在下面的代码中,我的转换过程中的某些内容失败了,因为
img.show()
(原始图像)显示正确,而img2.show()
显示全黑图片。 What am I missing?我错过了什么?
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 solution is to flatten the array before putting it into the image.解决方案是在将阵列放入图像之前将其展平。 I think PIL interprets multidimensional arrays as different color bands.
我认为 PIL 将多维数组解释为不同的色带。
img2.putdata(img_ints.astype(int).flatten())
For a more efficient way of loading images, check out如需更有效的图片加载方式,请查看
https://blog.eduardovalle.com/2015/08/25/input-images-theano/
https://blog.eduardovalle.com/2015/08/25/input-images-theano/
but use image.tobytes()
(Pillow) instead of image.tostring()
(PIL).但使用
image.tobytes()
(Pillow) 而不是image.tostring()
(PIL)。 . .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.