Issue
I have to count all the values in a matrix (2-d array) that are less than 200.
The code I wrote down for this is:
za=0
p31 = numpy.asarray(o31)
for i in range(o31.size[0]):
for j in range(o32.size[1]):
if p31[i,j]<200:
za=za+1
print za
o31
is an image and I am converting it into a matrix and then finding the values.
Is there a simpler way to do this?
Solution
The numpy.where
function is your friend. Because it's implemented to take full advantage of the array datatype, for large images you should notice a speed improvement over the pure python solution you provide.
Using numpy.where directly will yield a boolean mask indicating whether certain values match your conditions:
>>> data
array([[1, 8],
[3, 4]])
>>> numpy.where( data > 3 )
(array([0, 1]), array([1, 1]))
And the mask can be used to index the array directly to get the actual values:
>>> data[ numpy.where( data > 3 ) ]
array([8, 4])
Exactly where you take it from there will depend on what form you'd like the results in.
Answered By - abought
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.