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:

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
view raw np_count_elements.py hosted with ❤ by GitHub

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

>>> 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[0] * image.shape[1]
>>> 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] = 0
...
>>> if 1 not in d:
... d[1] = 0
...
>>>
>>> d
{0: 13, 1: 7}
>>> d[0]
13
>>> d[1]
7
view raw black_pixel_ratio.py hosted with ❤ by GitHub

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s