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?
The
numpy.wherefunction 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:
And the mask can be used to index the array directly to get the actual values:
Exactly where you take it from there will depend on what form you’d like the results in.