Image.fromarray只会产生黑色图像 [英] Image.fromarray just produces black image

查看:1084
本文介绍了Image.fromarray只会产生黑色图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to save a numpy matrix as a grayscale image using Image.fromarray. It seems to work on a random matrix, but not on a particular one (where there should appear a circle). Can anyone explain what I'm doing wrong?

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位整数.

Image.fromarray is poorly defined with floating-point input; it's not well documented but the function assumes the input is laid-out as unsigned 8-bit integers.

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

To produce the output you're trying to get, multiply by 255 and convert to uint8:

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

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

The reason it seems to work with the random array is that the bytes in this array, when interpreted as unsigned 8-bit integers, also look random. But the output is not the same random array as the input, which you can check by doing the above conversion on the random input:

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

Since the issue doesn't seem to be reported anywhere, I reported it on github: https://github.com/python-pillow/Pillow/issues/2856

这篇关于Image.fromarray只会产生黑色图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆