Count all values in a matrix greater than a value

gran_profaci picture gran_profaci · Oct 21, 2012 · Viewed 134k times · Source

I have to count all the values in a matrix (2-d array) that are greater 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.

My question is, is there a simpler way to do this?

Answer

nneonneo picture nneonneo · Oct 21, 2012

This is very straightforward with boolean arrays:

p31 = numpy.asarray(o31)
za = (p31 < 200).sum() # p31<200 is a boolean array, so `sum` counts the number of True elements