python count number of ones in a binary image
Question: What is the python module to count number of ones in a binary image ?

to rephrase,

I have a matrix that has only ones and zeros, it's of numpy array type and I
want to know how many ones are there.


Answer: You can simply use `sum`:

    
    
    >>> import numpy
    >>> n = numpy.random.randint(0, 2, size=(3,3))
    >>> n
    array([[1, 0, 1],
           [0, 1, 1],
           [1, 1, 1]])
    >>> n.sum()
    7
    

Since bools have integer values of 0/1 for False/True, even if the array had
elements that weren't 0 or 1 you could use a variant of this trick:

    
    
    >>> n = numpy.random.randint(0, 3, size=(3,3))
    >>> n
    array([[2, 2, 0],
           [0, 2, 0],
           [1, 1, 0]])
    >>> n == 1
    array([[False, False, False],
           [False, False, False],
           [ True,  True, False]], dtype=bool)
    >>> (n == 1).sum()
    2
    

