Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count all values in a matrix greater than a value

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?

like image 571
gran_profaci Avatar asked Oct 21 '12 07:10

gran_profaci


People also ask

How do I count true values in NumPy array?

Use numpy. count_nonzero() to count the number of True elements in a boolean array. Call numpy. count_nonzero(array) to return the number of True elements in a boolean array .

How do you count the number of elements in a 2D array in Python?

To get the length of a 2D Array in Python: Pass the entire array to the len() function to get the number of rows. Pass the first array element to the len() function to get the number of columns. Multiply the number of rows by the number of columns to get the total.


2 Answers

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 
like image 72
nneonneo Avatar answered Oct 02 '22 13:10

nneonneo


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.

like image 28
abought Avatar answered Oct 02 '22 13:10

abought