Image.fromarray只生成黑色图像

fla*_*awr 20 python numpy python-imaging-library

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

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')
Run Code Online (Sandbox Code Playgroud)

jak*_*vdp 30

Image.fromarray浮点输入定义不明确; 它没有很好地记录,但函数假设输入布局为无符号8位整数.

要生成您想要获得的输出,请乘以255并转换为uint8:

z = (z * 255).astype(np.uint8)
Run Code Online (Sandbox Code Playgroud)

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

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

pic1.png

Image.fromarray((zz * 255).astype('uint8'), mode='L').save('pic2.png')
Run Code Online (Sandbox Code Playgroud)

pic2.png

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

  • 也遇到了这个问题,并且 fromarray 的 Pillow 文档仍然没有提供任何帮助。 (2认同)
  • 我真的很困惑,直到我发现你的帖子!谢谢! (2认同)