python计算数组中每个数字出现次数,python count the occurrence of digist in an array

在进行图像处理的时候,我们经常会碰到 array 格式的数据,因为图像至少是二位数组。最近,我在看别人代码的时候,为了判断某个数组是否是二值图像的时候,我经常想要看变量中是否只存在 0 和 1 两种元素,所以上网找了比较好的实现方法,分享给大家。

参考资料: https://stackoverflow.com/questions/28663856/how-to-count-the-occurrence-of-certain-item-in-an-ndarray

 1 In [1]: import numpy as np                                                      
 2 
 3 In [2]: a=np.arange(1, 13).reshape(3, 4)                                        
 4 
 5 In [3]: a                                                                       
 6 Out[3]: 
 7 array([[ 1,  2,  3,  4],
 8        [ 5,  6,  7,  8],
 9        [ 9, 10, 11, 12]])
10 
11 In [4]: a[1,:]=100                                                              
12 
13 In [5]: a                                                                       
14 Out[5]: 
15 array([[  1,   2,   3,   4],
16        [100, 100, 100, 100],
17        [  9,  10,  11,  12]])
18 
19 In [6]: unique, counts = np.unique(a, return_counts=True)                       
20 
21 In [7]: b=dict(zip(unique, counts))                                             
22 
23 In [8]: b                                                                       
24 Out[8]: {1: 1, 2: 1, 3: 1, 4: 1, 9: 1, 10: 1, 11: 1, 12: 1, 100: 4}