Python PIL: Image.convert() mode "L" to "1" - how to change the value 127

361 views Asked by At

I have an image with only shades of gray and I need to convert it to only black and white ("1") but if I just use:

from PIL import Image
img = Image.open("img.jpg")
result = img.convert("1")
img.save("result.jpg")

pixels with values above 127 convert to white. Is there a way to change this border, for example to 220 so only the lightest pixels will be shown? Thank you

2

There are 2 answers

0
Mark Setchell On BEST ANSWER

You can most simply use the Image.point() method to threshold on a different value.

Let's make a 256x256 pixel linear gradient:

from PIL import Image
im = Image.linear_gradient("L")
im.save('a.png')

enter image description here

Now threshold all values above 200 to white, and others to black:

thresh200 = im.point(lambda i:255 if i>200 else 0)
thresh200.convert('L').save('b.png')

I added a thin red border around it so you can see the threshold is not at the middle (i.e. 127) but rather at 200, regardless of whether you are viewing on a light or dark background:

enter image description here

0
Suraj Shourie On

Check the documentation out. You need to use the "dither" argument for your usecase.