如何计算图像中的 RGB 或 HSV 通道组合?

问题描述:

我使用 python opencv 加载一个形状为 (30, 100, 3) 的图像,现在想计算所有颜色的频率,按颜色,我不是指单个通道,我指的是通道组合.含义 3 个频道列表,例如[255, 0, 0] 代表红色,[255, 255, 0] 代表黄色,[100, 100, 100] 代表另一种颜色.所以我希望将最后一个轴(通道)视为一个整体并计算其频率.

I use python opencv load an image which has shape (30, 100, 3), now want to count the frequency for all the colors, by color, I don't mean individual channel, I mean channel combination. Meaning 3 channel list, e.g. [255, 0, 0] for red, [255, 255, 0] for yellow, [100, 100, 100] for another color. So I want the last axis(channel) to be treated as a whole and count its frequency.

opencv 或 numpy 中是否有任何内置函数可以轻松地将 3 通道列表视为一个元素并计算其频率?

Is there any built-in function in opencv or numpy which can easily treat the 3 channel list as one element and count its frequency?

你可以使用 np.unique 及其新的 axis 参数功能,可以进行分组 -

You could use np.unique with its new axis argument functionality that does grouping -

np.c_[np.unique(im.reshape(-1,3), axis=0, return_counts=1)]

样品运行 -

In [56]: im
Out[56]: 
array([[[255, 255, 255],
        [255,   0,   0]],

       [[255,   0, 255],
        [255, 255, 255]]])

In [57]: np.c_[np.unique(im.reshape(-1,3), axis=0, return_counts=1)]
Out[57]: 
array([[255,   0,   0,   1],
       [255,   0, 255,   1],
       [255, 255, 255,   2]])