3

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?

gearhead
  • 787
  • 1
  • 6
  • 26

2 Answers2

2

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?

Siegfried Gevatter
  • 3,624
  • 3
  • 18
  • 13
-1

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.

Daniel Möller
  • 84,878
  • 18
  • 192
  • 214