Reputation: 45
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?
Upvotes: 2
Views: 2689
Reputation: 30605
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))
Upvotes: 2
Reputation: 2201
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
Upvotes: 0
Reputation: 4652
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]])
Upvotes: 2