簡體   English   中英

在 Numpy Ndarray 中查找唯一三元組的計數

[英]Finding count of unique triple in Numpy Ndarray

我有一些像這樣的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]
    ],
])

我需要找到圖像中每種顏色的計數,即以下 3 個元組的計數: [0, 0, 255],[255, 0, 0],[0, 255, 0] 在這種情況下:

# **Desired OUTPUT**
 unique  [[  0   0 255]
 [255   0   0]
 [  0 255   0]]
 counts  [8 21 3]

這就是我所做的:

print('AXIS 0 -----------------------------------')
unique0, counts0 = np.unique(img, axis=0, return_counts=True)
print('unique0 ', unique0)
print('counts0 ', counts0)

這是 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]

嘗試使用axis=1 (counts1 [2 1 5])時,我得到了類似的結果。

我還嘗試將元組作為軸輸入axis=(0, 1) ,它返回錯誤TypeError: an integer is required (got type tuple)

任何想法我做錯了什么?

你可以這樣做:

elements, counts = np.unique(img.reshape((-1, 3)), axis=0, return_counts=True)
print(elements, counts)

Output

[[  0   0 255]
 [  0 255   0]
 [255   0   0]] [ 8  3 21]

首先使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM