简体   繁体   中英

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!

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.

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM