1

I have an image.

I would like to go over that image, pixel by pixel, and any pixel that is not black should be turned to white. How do I do this?

(Python).

Thanks!

3 Answers 3

6

The most efficient way is to use the point function

def only_black(band):
    if band > 0:
        return 255
    return 0
result = im.convert('L').point(only_black)

This is what the PIL documentation has to say about this:

When converting to a bilevel image (mode "1"), the source image is first converted to black and white. Resulting values larger than 127 are then set to white, and the image is dithered. To use other thresholds, use the point method.

1
  • Since the band argument of the only_black function will be an integer 0≤band<256, only_black could contain just the following line of code: return band and 255
    – tzot
    Jul 4, 2009 at 3:05
3

You should use the point function, which exists specifically for this reason.

converter= ( (0,) + 255*(255,) ).__getitem__
def black_or_white(img):
    return img.convert('L').point(converter)
1
  • Considering that for an "L" image the converter function will be called 256 times at the most (check the Image.point documentation), it is faster than the one suggested by Nadia, but not that faster :)
    – tzot
    Jul 4, 2009 at 3:01
1

You might want to check out the following library:

http://effbot.org/imagingbook/image.htm

Especially:

im.getpixel(xy) => value or tuple

and

im.putpixel(xy, colour)
2
  • 2
    The putpixel function is very slow Jul 3, 2009 at 17:34
  • Good to know! I've never used PIL I just recalled running across it at one point working with Python. Jul 3, 2009 at 18:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.