I have grayscale image whose background is, on a 0-255 color scale, a mid-white color with an average pixel color value of 246; the foreground is mid-grey with an average pixel-color value of 186.
I would like to ‘shift’ every pixel above 246 to 255, every pixel below 186 to zero, and ‘stretch’ everything between. Is there any ready-made algorithm/process to do this in numpy or python, or must the new levels/histogram be calculated ‘manually’ (as I have done thus far)?
This is the equivalent of, in Gimp or Photoshop, opening the levels window and selecting, with the white and black eyedropper respectively, a light region we want to make white and a darker region we want to make black: the application modifies the levels/histogram (‘stretches’ the values between the points selected) accordingly.
Some images of what I’m attempting:
2
Answers
Here’s one way –
As per OP, the criteria set was :
‘shift’ every pixel above
246
to255
, hence247
and above should become255
.every pixel below
186
tozero
, hence185
and below should become0
.Hence, based on above mentioned two requirements,
186
should become something greater than0
and so on, until246
which should be lesser than255
.Alternatively, we can also use
np.where
to make it a bit more compact –Sample run –
If your picture is uint8 and typical picture size, one efficient method is setting up a lookup table:
For smaller images it is faster (on my setup it crosses over at around 100,000 gray scale pixels) to transform directly: