quilby
quilby

Reputation: 3271

Cleaning an image to only black

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!

Upvotes: 1

Views: 838

Answers (3)

Scanningcrew
Scanningcrew

Reputation: 790

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)

Upvotes: 1

Nadia Alramli
Nadia Alramli

Reputation: 114933

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.

Upvotes: 6

tzot
tzot

Reputation: 95911

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)

Upvotes: 3

Related Questions