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
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')
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: