gearhead
gearhead

Reputation: 807

Can't format BMP image data to 1 bit per pixel in PIL

I have a black and white bmp image that I need to access 1 pixel at a time. I've found the following code online, but instead of each bit having a value of 1 or 0, its 255 or 0.

import Image
img = Image.open(filename)
img = img.convert('1')
pix = img.load()

Doing the conversion myself, pixel by pixel, is extremely slow.

can someone tell my why the above methods aren't working?

Upvotes: 3

Views: 2687

Answers (2)

Daniel Möller
Daniel Möller

Reputation: 86650

Perhaps numpy is a good solution:

import numpy as np
from PIL import Image

#here, the image will be a numpy array
img = np.array(Image.open(filename)) / 255.

If you want to convert it back to image:

img = Image.fromarray(img)

A little detail: Converting to numpy will flip x and y. Converting back will restore the original positions.

Upvotes: -1

Siegfried Gevatter
Siegfried Gevatter

Reputation: 3694

You could convert it like this:

img.point(lambda x: bool(x))

But why do you need it to be 0/1 (rather than 0/255) in the first place?

Upvotes: 2

Related Questions