2

I am converting a code from Matlab to Python. The code in Matlab is:

x = find(sEdgepoints > 0 & sNorm < lowT);
sEdgepoints(x)=0;

Both arrays are of same size, and I am basically creating a mask.

I read here that nonzero() in numpy is equivalent to find(), so I used that. In Python, I have dstc for sEdgepoints and dst for sNorm. I have also directly put in lowT = 60. So, the code was

x = np.nonzero(dstc > 0 and dst < 60)
dstc[x] = 0

But, I get following error:

Traceback (most recent call last):
File "C:\Python27\Sheet Counter\customsobel.py", line 32, in <module>
    x = np.nonzero(dstc > 0 and dst < 60)
ValueError: The truth value of an array with more than one element is 
ambiguous. Use a.any() or a.all()

I read about the usage of a.any()/a.all() in this post, and I am not sure how that will work. So, I have two questions: 1. If it does, which array to use? 2. If I am correct and it does not work, how to convert the code?

Epsilon7
  • 45
  • 1
  • 8

3 Answers3

2

Try np.argwhere() (and note the importance of the () around the inequalities):

>>X=np.array([1,2,3,4,5])
>>Y=np.array([7,6,5,4,3])
>>ans = np.argwhere((X>3) & (Y<7))
>>ans 

array([[3],
   [4]])
qbzenker
  • 4,412
  • 3
  • 16
  • 23
2

and does boolean operation and numpy expects you to do bitwise operation, so you have to use & i.e

x = np.nonzero((dstc > 0) & ( dst < 60))
Bharath M Shetty
  • 30,075
  • 6
  • 57
  • 108
0

You could implement it yourself like:

x = [[i,j] for i, j in zip(sEdgepoints , sNorm ) if i > 0 and j < lowT]

Will give you a list of of lists corresponding to your the matching constraints. I guess this might not be exactly what you are looking for.

Maybe look at the pandas module, it makes masking more comfortable than plain python or numpy: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mask.html

meow
  • 2,062
  • 2
  • 17
  • 27