首页 > 解决方案 > 计算唯一的 rgb

问题描述

我已经找到了一个工作代码,但不了解这些行的所有内容:

counter = np.unique(img.reshape(-1, img.shape[2]), axis=0)
print(counter.shape[0])

特别是这些值:

-1, img.shape[2], axis=0

-1 是做什么的,为什么是形状 2,为什么是轴 0?在那之后,我们为什么要打印 shape[0]?

标签: python

解决方案


如果您不理解复杂的句子,请始终将它们分解并打印形状。

print(img.shape)
img2 = img.reshape(-1, img.shape[2]) # reshape the original image into -1, 3; -1 is placeholder, so lets say you have a 
                                     # numpy array with shape (6,2), if you reshape it to (-1, 3), we know the second dim = 3
                                     # first dim = (6*2)/3 = 4, so -1 is replaced with 4
print(img2.shape)

counter = np.unique(img2, axis=0) # find unique elemenst
'''
numpy.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)[source]
Find the unique elements of an array.

Returns the sorted unique elements of an array. There are three optional outputs in addition to the unique elements:

the indices of the input array that give the unique values
the indices of the unique array that reconstruct the input array
the number of times each unique value comes up in the input array
'''
print(counter)
print(counter.shape) # as, we have separate axis, so the channels are shown in dim 2
print(counter.shape[0])

但是,这个可能不正确,因为它没有考虑跨通道的唯一 RGB。

因此,以下是更好的方法,您将数组展平以获取列表,然后使用 set 查找唯一元素,最后打印集合的 len。

一个方便的快捷方式是 ->

print(len(set(img.flatten())))

推荐阅读