1

I know that a binary image is matrix with 0 and 1 values. If I generate a matrix with numpy having 0 and 1 elements and then I use pillow library from python to read the image from the numpy array, the image is black. Why this is happen?

from PIL import Image
import numpy
matrix = numpy.random.randint(2, size=(512,512))
img =  Image.fromarray(matrix)
img.save(test.png)
1
  • By way of explanation, your matrix is probably of type uint32 - because you didn't specify the dtype when creating it - which means it uses 4 bytes per pixel rather than the 1-bit you intended. Which means that black is represented by 0 and white is represented by 4,294,967,295, so your values of 0 and 1 are all going to look pretty black on that range. Commented May 16, 2020 at 10:39

1 Answer 1

3

What you want is a single bit PNG image. cv2 and PIL.Image both support this type of images.

from PIL import Image
import numpy
# boolean matrix
matrix = numpy.random.randint(2, size=(512,512)).astype(bool)
img =  Image.fromarray(matrix)
img.save("test.png", bits=1,optimize=True)
Sign up to request clarification or add additional context in comments.

2 Comments

Your answer works correctly, but it might be worth noting that you are creating an array at least 8x bigger in terms of RAM usage and taking around 6-7x longer than necessary in terms of time and then reducing it afterwards, with .astype() rather than creating it with the intended type up-front... matrix = numpy.random.randint(2, size=(512,512), dtype=np.uint8)
Yes, I was going to mention that, but then didn't. Tried to keep it similar to the OP's question. Also, I see that numpy.random.choice generates float64 and then converts to bool, so I guess it would have more or less same implications

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.