列表在ndarray中的出现

Occurrence of list in ndarray

我有一个 RGB 图像 -ndarray-,我想计算此图像中 [255,0,0] 或 [0,0,255] 等颜色的出现次数。

图像数据示例

np.ones((3, 3, 3)) * 255

array([[[255., 255., 255.],
        [255., 255., 255.],
        [255., 255., 255.]],
       [[255., 255., 255.],
        [255., 255., 255.],
        [255., 255., 255.]],
       [[255., 255., 255.],
        [255., 255., 255.],
        [255., 255., 255.]]])

所以我想要这样的东西

{
'[255,255,255]' : 9,
}

一个解决方案可能是 Counter 函数:

from collections import Counter
import numpy as np

# Generate some data
data = np.ones((10, 20, 3)) * 255

# Convert to tuple list
data_tuple = [ tuple(x) for x in data.reshape(-1,3)]
Counter(data_tuple)

Returns:

Counter({(255.0, 255.0, 255.0): 200})

这是一种使用 NumPy 的方法。作为 0-255 范围内的值,我们可以将行视为具有三个 f8 类型元素的元组,并使用 np.unique 来计算原始 ndarray 中实际行的出现次数。使用 nakor 数组:

a = np.ones((10, 20, 3)) * 255

然后我们可以这样做:

vals, counts = np.unique(a.view('f8,f8,f8'), return_counts=True)

其中:

print(vals)
array([(255., 255., 255.)],
      dtype=[('f0', '<f8'), ('f1', '<f8'), ('f2', '<f8')])

print(counts)
array([200])

虽然可以使用 Counteropencv histogram function 来计算每个像素的频率,但对于特定像素,使用此方法效率更高:

import numpy as np

ar = np.ones([3,3,3]) *255
ar[1,1,:] = [0, 0, 200]

pixels = dict()
pixels['[255, 255, 255]'] =  np.sum(np.all(ar == [255,255, 255], axis = 2))
pixels['[0, 0, 200]'] =  np.sum(np.all(ar == [0, 0, 200], axis = 2)) 

结果:{'[255, 255, 255]': 8, '[0, 0, 200]': 1}