views:

145

answers:

3

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!

+1  A: 

You might want to check out the following library:

http://www.pythonware.com/library/pil/handbook/image.htm

Especially:

im.getpixel(xy) => value or tuple

and

im.putpixel(xy, colour)
Scanningcrew
The putpixel function is very slow
Nadia Alramli
Good to know! I've never used PIL I just recalled running across it at one point working with Python.
Scanningcrew
+6  A: 

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.

Nadia Alramli
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
ΤΖΩΤΖΙΟΥ
+3  A: 

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)
ΤΖΩΤΖΙΟΥ
Ooh, this looks fast.
Kiv
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 :)
ΤΖΩΤΖΙΟΥ