user16971617
user16971617

Reputation: 535

Skipping 0 when doing frequency count

This line of code does the frequency count of my image which is 2D numpy array. But I would like to ignore 0, is there a simple way to skip it?

freq_count = dict(zip(*np.unique(img_arr.ravel(), return_counts=True)))
for i in freq_count.keys(): 
 # Do something

Upvotes: 0

Views: 46

Answers (1)

mozway
mozway

Reputation: 261870

You can slice out the 0s:

freq_count = dict(zip(*np.unique(img_arr[img_arr!=0], return_counts=True)))

But honestly, it might be faster and more explicit to just skip the 0 in the loop or remove it from the dictionary:

freq_count = dict(zip(*np.unique(img_arr, return_counts=True)))

if 0 in freq_count:
    del freq_count[0]

for i in freq_count:
    pass

Upvotes: 1

Related Questions