UWU gg
UWU gg

Reputation: 37

How to fix this error "fromarray" function from PIL module python?

I just try to learn how to create image from array with replit.com

import numpy as np
from PIL import Image
emtpy=np.zeros((24,24))
emtpy[:,:]=[0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1]
print(emtpy)
img=Image.fromarray(emtpy, "1")
img.save("test.png")

This is what i got:
![enter image description here (it's 24x24 matrix)

And the image:
enter image description here

why they seem not similar to the array?

I already try another mode of fromarray,by change "1" to "L" and other, they still not work
enter image description here
("L" mode)

My expectation is: enter image description here

Upvotes: 1

Views: 255

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207405

If you look at your data you'll see it is float, because it has a decimal point.

You need an unsigned 8-bit integer:

emtpy=np.zeros((24,24), dtype=np.uint8)

Then, when you create an Image object you will need to do this to be in the correct range for 8-bit pixels, i.e. 0..255:

img=Image.fromarray(emtpy*255, "L")

Upvotes: 1

Related Questions