jax
jax

Reputation: 4197

How to generate a PBM with a combination of 0 & 1 using python

[[0,1,0,1,1,0,0,0,0,1,0,1,0,1,0,1]
[0,0,0,0,0,1,1,1,1,0,1,0,1,0,1,1]
[0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0]
[0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,0]
[0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1]]

How can I generate a Binary image with the about matrics, in PBM formate? As there are 16 columns and 5 rows. I'hv searched a few methods that can convert an image into binary one but not able to find a way to generate a binary image using this kinda matrix.

and

How much amount of memory will be used to represent a 0 or 1 on a memory in a binary image? Let's suppose a binary image only has 1 pixel. How much memory will be used to represent that one pixel on the image? As in the case of the grayscale image, It would take 8 bytes for a single pixel. In the case of the binary image, where it only takes either 0 or 1, doe it takes 2 bits two represent a single pixel?

Thanks.

Upvotes: 1

Views: 464

Answers (1)

Vasilis G.
Vasilis G.

Reputation: 7846

You could use the Pillow library in order to create an pbm image from the above data:

from PIL import Image

binaryData = [[0,1,0,1,1,0,0,0,0,1,0,1,0,1,0,1],
[0,0,0,0,0,1,1,1,1,0,1,0,1,0,1,1],
[0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0],
[0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,0],
[0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1]]

pixelData = [255 if elem else 0 for row in binaryData for elem in row]

img = Image.new("L", (len(binaryData[0]), len(binaryData)))
img.putdata(pixelData)
img.save("image.pbm")

Upvotes: 2

Related Questions