I have an image represented as numpy array which has values of 0 and 255 (no other value within the range). What is the best way to convert it to 0 and 1 array.
my_array = np.array([255,255,0,0])
my_array = my_array / 255
Will output
array([ 1., 1., 0., 0.])
In other words, it will work to normalize all values in the range of 0-255 (even though you said it's the only 2 values, it will work for everything in between as well, while keeping the ratios)
Sounds like a job for numpy.clip
:
>>> a = np.array([0, 255, 0, 255, 255, 0])
>>> a.clip(max=1)
array([0, 1, 0, 1, 1, 0])
From the docs:
Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With