python - Image.fromarray 只产生黑色图像

标签 python numpy python-imaging-library

我正在尝试使用 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')

最佳答案

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')

pic1.png

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

pic2.png

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

关于python - Image.fromarray 只产生黑色图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47290668/

相关文章:

python - ImageTk.PhotoImage 崩溃

python - 在 Python 中继承子方法

python - 如何使用hyperopt对Keras深度学习网络进行超参数优化?

Python 3 : Calling a Function from a class, self

python - 数组 dtype ('|S58' 中竖线的含义是什么)

python - 在 numpy.where 中访问对象方法?

python - 如何在 Python 中从蒙版分割图像创建轮廓(粗细可控)?

python-3.x - 如何在 Django 中正确创建 InMemoryUploadedFile 对象

python - 最大限度地分散所有护士的调度

python - 使用类的 __call__ 方法作为 Numpy curve_fit 的输入