From the histogram I am generated a list of lists with the following aspect,
[[9.]
[3.]
[1.]
[1.]
[2.]
[1.]
[0.]
[0.]
[0.]]
My intention is to count how many inner lists have a value other than zero, in this case 6. That as such is no problem, but I would like to do it using list comprehension .
This is what I have tried,
histr_b = cv2.calcHist([crop_img],[0],None,[18],[2,20])
bb = 0
bb = [bb+1 for h in histr_b if h > 0]
The problem is that the only thing I get is to put a 1 in case it h
is greater than 0. How should it be done? Obviously now I can do one len(bb)
and know how many there are. But the grace is that the previous line of code is capable of doing that count.
Greetings and health to all!
Instead of a compressed list use better
sum
and a generator expression, if you just want to count creating a list is a waste of resources:Although what you have is a Numpy array, not a list , in which case for this particular example, you should do:
either
but better take advantage of NumPy:
which should be the preferred option for efficiency (*see end of answer). You could also use
numpy.sum
:If there is more than one column (which is not the case) a previous slicing must be done or it will count those greater than 0 in all:
or use the argument
axis
with value 0, which will count the ones greater than zero per column:the output is another array with an integer for each column whose value is the number of numbers greater than 0 in that column.
*If we make a small comparison of execution times:
The clear winner is
numpy.count_nonzero
.