Image.fromarray only creates a black image

I am trying to save a numpy matrix as a grayscale image using Image.fromarray . It seems that it works on a random matrix, but not on a specific one (where the circle should appear). Can someone 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') 
+3
source share
1 answer

Image.fromarray poorly defined using floating point input; it is not well documented, but the function assumes that the input data is laid out in the form of 8-bit unsigned integers.

To create the output you are trying to get, multiply by 255 and convert to uint8 :

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

The reason it seems to work with a random array is because the bytes in this array, 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 a random input:

 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

Since the problem is not reported anywhere, I reported it on github: https://github.com/python-pillow/Pillow/issues/2856

+3
source

All Articles