二维 numpy 数组中的最大频率一维数组

Max frequency 1d array in a 2d numpy array

我有一个二维 numpy 数组:

array([[21, 17, 11],
   [230, 231, 232],
   [21, 17, 11]], dtype=uint8)

我想找到更频繁的一维数组。对于上面的二维数组,它是: [21, 17, 11]。它类似于统计数据中的模式。

我们可以使用 np.unique 及其可选参数 return_counts 来获取每个唯一行的计数,最后获取 argmax() 以选择具有最大计数的行 -

# a is input array
unq, count = np.unique(a, axis=0, return_counts=True)
out = unq[count.argmax()]

对于uint8类型的数据,我们也可以通过将每一行减少为一个标量,然后使用np.unique-

转换为1D
s = 256**np.arange(a.shape[-1])
_, idx, count = np.unique(a.dot(s), return_index=True, return_counts=True)
out = a[idx[count.argmax()]]

如果我们正在处理 3D 的彩色图像(最后一个轴是颜色通道)并且想要获得最主要的颜色,我们需要使用 a.reshape(-1,a.shape[-1]) 重塑形状然后馈送它到建议的方法。