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?
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 .
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With