【问题标题】:PIL/Pillow convert Image to list and back againPIL/Pillow 将图像转换为列表并再次返回
【发布时间】:2016-04-20 14:27:46
【问题描述】:

我正在尝试打开 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

【问题讨论】:

    标签: python python-3.x numpy python-imaging-library pillow


    【解决方案1】:

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

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

    如需更有效的图片加载方式,请查看

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-13
      • 2015-01-19
      • 2013-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-22
      • 1970-01-01
      相关资源
      最近更新 更多