Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array values 0 and 255 to corresponding 0 and 1 array

Tags:

python

numpy

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.

like image 300
matchifang Avatar asked Dec 10 '22 10:12

matchifang


2 Answers

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)

like image 72
Ofer Sadan Avatar answered May 11 '23 16:05

Ofer Sadan


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.

like image 41
randomir Avatar answered May 11 '23 16:05

randomir