AlexDragos
AlexDragos

Reputation: 91

How to generate a random binary image?

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)

Upvotes: 1

Views: 1596

Answers (1)

dumbPy
dumbPy

Reputation: 1518

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)

Upvotes: 3

Related Questions