【问题标题】:Image.fromarray just produces black imageImage.fromarray 只产生黑色图像
【发布时间】:2018-04-27 16:33:35
【问题描述】:

我正在尝试使用Image.fromarray 将 numpy 矩阵保存为灰度图像。它似乎适用于随机矩阵,但不适用于特定矩阵(应该出现一个圆圈)。谁能解释我做错了什么?

from PIL import Image
import numpy as np
radius = 0.5
size = 10
x,y = np.meshgrid(np.linspace(-1,1,size),np.linspace(-1,1,size))
f = np.vectorize(lambda x,y: ( 1.0 if x*x + y*y < radius*radius else 0.0))
z = f(x,y)
print(z)
zz = np.random.random((size,size))
img = Image.fromarray(zz,mode='L') #replace z with zz and it will just produce a black image
img.save('my_pic.png')

【问题讨论】:

  • 您需要将其缩放到 255 并使用我认为的 uint8/16 dtypes。
  • 但是zz 也只是一个值在0到1之间的矩阵,它似乎工作得很好?
  • 你是说zz 有效,但z 无效?
  • 是的,z 是我真正想要保存的那个,zz 只是作为一个确实有效的示例(与z 相比),它们都有 dtype @ 987654330@.

标签: python numpy python-imaging-library


【解决方案1】:

Image.fromarray 用浮点输入定义不好;它没有很好的文档记录,但该函数假定输入布局为无符号 8 位整数。

要产生您想要得到的输出,乘以 255 并转换为 uint8

z = (z * 255).astype(np.uint8)

它似乎与随机数组一起工作的原因是这个数组中的字节,当解释为无符号 8 位整数时,看起来也是随机的。但是输出和输入不是同一个随机数组,可以通过对随机输入做上述转换来检查:

np.random.seed(0)
zz = np.random.rand(size, size)
Image.fromarray(zz, mode='L').save('pic1.png')

Image.fromarray((zz * 255).astype('uint8'), mode='L').save('pic2.png')

由于该问题似乎没有在任何地方报告,我在github上报告了它:https://github.com/python-pillow/Pillow/issues/2856

【讨论】:

  • 为什么要转成uint8?
  • @Goldname 我认为这就是 Pillow 用于L (grayscale) mode.
  • 也被这个抓住了,而且 fromarray 的 Pillow 文档仍然没有帮助。
  • 在找到你的帖子之前我真的很困惑!谢谢!
猜你喜欢
  • 2017-03-13
  • 1970-01-01
  • 2018-09-15
  • 2014-10-12
  • 1970-01-01
  • 2016-02-24
  • 2018-10-17
  • 2011-09-06
  • 1970-01-01
相关资源
最近更新 更多