[英]Finding count of unique triple in Numpy Ndarray
I have some image in ndarray form like this:我有一些像这样的ndarray形式的图像:
# **INPUT**
img = np.array(
[
[
[0, 0, 255],
[0, 0, 255],
[0, 0, 255],
[0, 0, 255],
[0, 0, 255],
[0, 0, 255],
[0, 0, 255],
[0, 0, 255]
],
[
[255, 0, 0],
[255, 0, 0],
[255, 0, 0],
[0, 255, 0],
[0, 255, 0],
[255, 0, 0],
[255, 0, 0],
[255, 0, 0]
],
[
[255, 0, 0],
[0, 255, 0],
[255, 0, 0],
[255, 0, 0],
[255, 0, 0],
[255, 0, 0],
[255, 0, 0],
[255, 0, 0]
],
[
[255, 0, 0],
[255, 0, 0],
[255, 0, 0],
[255, 0, 0],
[255, 0, 0],
[255, 0, 0],
[255, 0, 0],
[255, 0, 0]
],
])
I need to find count of each color in my image,ie count of 3 following tuples: [0, 0, 255],[255, 0, 0],[0, 255, 0] .我需要找到图像中每种颜色的计数,即以下 3 个元组的计数: [0, 0, 255],[255, 0, 0],[0, 255, 0] 。 In this case:在这种情况下:
# **Desired OUTPUT**
unique [[ 0 0 255]
[255 0 0]
[ 0 255 0]]
counts [8 21 3]
this is what I have done:这就是我所做的:
print('AXIS 0 -----------------------------------')
unique0, counts0 = np.unique(img, axis=0, return_counts=True)
print('unique0 ', unique0)
print('counts0 ', counts0)
This is the output:这是 output:
AXIS 0 -----------------------------------
unique0 [[[ 0 0 255]
[ 0 0 255]
[ 0 0 255]
[ 0 0 255]
[ 0 0 255]
[ 0 0 255]
[ 0 0 255]
[ 0 0 255]]
[[255 0 0]
[ 0 255 0]
[255 0 0]
[255 0 0]
[255 0 0]
[255 0 0]
[255 0 0]
[255 0 0]]
[[255 0 0]
[255 0 0]
[255 0 0]
[ 0 255 0]
[ 0 255 0]
[255 0 0]
[255 0 0]
[255 0 0]]
[[255 0 0]
[255 0 0]
[255 0 0]
[255 0 0]
[255 0 0]
[255 0 0]
[255 0 0]
[255 0 0]]]
counts0 [1 1 1 1]
I get similar result when trying with axis=1
(counts1 [2 1 5]).尝试使用axis=1
(counts1 [2 1 5])时,我得到了类似的结果。
I have also tried giving a tuple as axis input, axis=(0, 1)
, which return the error TypeError: an integer is required (got type tuple)
.我还尝试将元组作为轴输入axis=(0, 1)
,它返回错误TypeError: an integer is required (got type tuple)
。
Any ideas what I am doing wrong?任何想法我做错了什么?
You could do:你可以这样做:
elements, counts = np.unique(img.reshape((-1, 3)), axis=0, return_counts=True)
print(elements, counts)
Output Output
[[ 0 0 255]
[ 0 255 0]
[255 0 0]] [ 8 3 21]
Start by using np.concatenate
to concatenate the ndarray along the first axis, and then use np.unique
as you where doing, setting return_counts=True
, which will return the counts of the flattened 2D
array:首先使用np.concatenate
沿第一个轴连接 ndarray,然后使用np.unique
设置return_counts=True
,这将返回扁平2D
数组的计数:
unique, counts = np.unique(np.concatenate(mg), axis=0, return_counts=True)
print(unique)
[[ 0 0 255]
[ 0 255 0]
[255 0 0]]
print(counts)
# array([ 8, 3, 21], dtype=int64)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.