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?

3 Answers 3

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))
Sign up to request clarification or add additional context in comments.

Comments

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]])

2 Comments

This does work, but sorry I can't upvote as my reputation is not enough. Thanks!
No problem at all -- I was there too. Glad you have a solution!
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.