The answer is as simple as:
mask = im == 5
which gives you a Boolean mask which is True wherever the image has a pixel with the value 5. You can then multiply that by 255 if you want it white wherever the image is 5, or by 5 if you want it to have the value 5 wherever the original is 5.
Note also that this solution requires ONE byte per pixel because it gives you a Boolean mask, whereas using unadorned np.where()
will take EIGHT bytes per pixel because it gives you an array of np.uint64
.
Note also that this is 16 times faster than np.where()
on my machine:
%timeit mask = im == 192
937 ns ± 1.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
versus:
%timeit a = np.where(im==192, 192, 0)
15.1 µs ± 8.27 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Let's make an example, not with 1 ,2, 3, 4, 5 because they are too dark to see, so let's make squares with brightness 64, 128 and 192:
import numpy as np
# Make black image
im = np.zeros((100,300), np.uint8)
im[20:80, 20:80] = 64 # dark grey square on left
im[20:80, 120:180] = 128 # mid-grey square in centre
im[20:80, 220:280] = 192 # light grey square on right

And then, the code you need to select the right-hand square which has value 192 is this:
mask = im == 192
