# Python Numpy count elements

As you already know, in order to calculate non-zero elements in your np array, you can use numpy.count_nonzero. But how about 0? How about an expression? Well, as it turns out, you can calculate 0s with count_nonzero() as well. Seems counter intuitive? Maybe not. Let’ see an example:

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 import numpy as np x = np.arange(20).reshape(4,5) y = x % 3 == 0 y = y.astype(int) # optional, if dealing with only 1s and 0s # simple np.count_nonzero(y == 1) # 7 np.count_nonzero(y == 0) # 13 (y == 1).sum() # 7 (y == 0).sum() # 13 # slightly complex np.count_nonzero(x > 5) # 14 (x > 9).sum() # 10

Another example …

So let’s say you were doing some statistical image computation on a binary (0-1) image (whose pixels are either 0 or 1, i.e. black or white) and you needed to compute a black pixel ratio, in other words, ratio of black pixels to total pixels. In addition to what we discussed above, there seems also another way to do this.

The second approach below is particularly handy, if you are interested in calculating the total number of white and black pixel counts in your binary image. The caveat in the second approach is, whilst, working with complete white or complete black image, your dictionary (here, the variable d) would not have a key for 0 and 1 respectively. Lines 25 and 28 should take care of that. But if this does not apply for you, then certainly you can ignore this consideration

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 >>> image array([[1, 0, 0, 1, 0], [0, 1, 0, 0, 1], [0, 0, 1, 0, 0], [1, 0, 0, 1, 0]]) >>> black_pixel_count = (image == 0).sum() >>> total_pixel_count 20 >>> total_pixel_count = image.shape * image.shape >>> total_pixel_count 20 >>> black_pixel_ratio = black_pixel_count / float(total_pixel_count) >>> black_pixel_ratio 0.65000000000000002 >>> import collections >>> k, v = np.unique(y, return_counts=True) >>> k array([0, 1]) >>> v array([13, 7]) >>> d = dict(zip(k,v)) >>> if 0 not in d: ... d = 0 ... >>> if 1 not in d: ... d = 0 ... >>> >>> d {0: 13, 1: 7} >>> d 13 >>> d 7