0

I am trying to convert an 8-by-8 numpy array of binary format (0 represents black and 1 represents white). This is what I run:

from PIL import Image

data = im.fromarray(array)     # array is an 8*8 binary numpy
data.save('dummy_pic.png')

But in the output I get a fully black square. Could anyone give me a hand please?

1 Answer 1

1

Black square is probably very dark gray, because you may have np.array with uint8 datatype, which has range of 0-255, not 0-1 like binary array. Try changing array datatype to bool, or scale values to 0-255 range.

Here is code snippet in which binary array is generated and displayed. If you scale by smaller value, circle will become slightly darker.

from PIL import Image
import numpy as np

# Generating binary array which represents circle
radius = 0.9
size = 100
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))
array = f(x,y)

# Solution 1: 
# convert np.array to bool datatype
array = (array).astype(np.bool)

# Solution 2:
# scale values to uint8 maximum 255
array = ((array) * 255).astype(np.uint8)


img = Image.fromarray(array)
display(img)

Result: White circle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.