Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy matrix binarization using only one expression

Tags:

python

numpy

I am looking for a way to binarize numpy N-d array based on the threshold using only one expression. So I have something like this:

np.random.seed(0) np.set_printoptions(precision=3) a = np.random.rand(4, 4) threshold, upper, lower = 0.5, 1, 0 

a is now:

array([[ 0.02 ,  0.833,  0.778,  0.87 ],        [ 0.979,  0.799,  0.461,  0.781],        [ 0.118,  0.64 ,  0.143,  0.945],        [ 0.522,  0.415,  0.265,  0.774]]) 

Now I can fire these 2 expressions:

a[a>threshold] = upper a[a<=threshold] = lower 

and achieve what I want:

array([[ 0.,  1.,  1.,  1.],        [ 1.,  1.,  0.,  1.],        [ 0.,  1.,  0.,  1.],        [ 1.,  0.,  0.,  1.]]) 

But is there a way to do this with just one expression?

like image 415
Salvador Dali Avatar asked Sep 01 '15 01:09

Salvador Dali


People also ask

How do I create a one direction numpy array?

Python Numpy – Create One Dimensional Array One dimensional array contains elements only in one dimension. In other words, the shape of the numpy array should contain only one value in the tuple. To create a one dimensional array in Numpy, you can use either of the array(), arange() or linspace() numpy functions.

Which function creates a 2D array with all values 1?

We can create a 2D array by passing a list to the array() function of NumPy.


1 Answers

We may consider np.where:

np.where(a>threshold, upper, lower) Out[6]:  array([[0, 1, 1, 1],        [1, 1, 0, 1],        [0, 1, 0, 1],        [1, 0, 0, 1]]) 
like image 70
CT Zhu Avatar answered Oct 17 '22 20:10

CT Zhu