Using python PIL to turn a RGB image into a pure black and white image

后端 未结 5 1981
逝去的感伤
逝去的感伤 2020-12-02 07:06

I\'m using the Python Imaging Library for some very simple image manipulation, however I\'m having trouble converting a greyscale image to a monochrome (black and white) ima

5条回答
  •  渐次进展
    2020-12-02 07:27

    A PIL only solution for creating a bi-level (black and white) image with a custom threshold:

    from PIL import Image
    img = Image.open('mB96s.png')
    thresh = 200
    fn = lambda x : 255 if x > thresh else 0
    r = img.convert('L').point(fn, mode='1')
    r.save('foo.png')
    

    With just

    r = img.convert('1')
    r.save('foo.png')
    

    you get a dithered image.

    From left to right the input image, the black and white conversion result and the dithered result:

    You can click on the images to view the unscaled versions.

提交回复
热议问题