I am trying write a contrast adjustment for images in gray scale colors but couldn\'t find the right way to do it so far. This is what I came up with:
import nu
The easiest way to increase the contrast (i.e. pull apart darker and brighter pixels), is just to "stretch out" the current existing range (144 to 216) over the entire spectrum (0 to 255):
Setup, same way as in this answer.
import numpy as np
from PIL import Image
pixvals = np.array(Image.open("image.png").convert("L"))
And then expand the range
pixvals = ((pixvals - pixvals.min()) / (pixvals.max()-pixvals.min())) * 255
Image.fromarray(pixvals.astype(np.uint8))
The result is effectively the same as in this answer, just with slightly less code:
Now, in this image, that might be enough. However some images might have a few pixels that are really close to 0 or 255, which would render this method ineffective.
Here numpy.percentile() comes to the rescue. The idea is to "clip" the range in which pixels are allowed to exist.
minval = np.percentile(pixvals, 2)
maxval = np.percentile(pixvals, 98)
pixvals = np.clip(pixvals, minval, maxval)
pixvals = ((pixvals - minval) / (maxval - minval)) * 255
Image.fromarray(pixvals.astype(np.uint8))
Which results in a little bit higher contrast, since all values below 2% and above 98% are effectively removed. (Play with these values as you see fit)