在numpy中以维度的形式获取数字的重复

Get the repetition of number in the form of dimension in numpy

我有一个 10x20 的 numpy 数组

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

我想以维度数组的形式重复数字 0(0 的岛)。就像在上面的例子中,如果我将数字 0 作为参数传递,函数应该从上到下通过矩阵,然后从左到右产生维数组。上面例子的输出应该是

#Zeroes repetition dimensions
[[20,4],[3,5],[2,5]]

我怎样才能得到这个输出。有任何 numpy 函数可以做到这一点吗?提前致谢。

我会为此使用 itertools groupby

import numpy as np
from itertools import groupby
from collections import Counter
arr=np.array([[255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255],
 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
 [255,255,255,255,255,255,255,0,0,0,255,255,0,0,255,255,255,255,255,255],
 [255,255,255,255,255,255,255,0,0,0,255,255,0,0,255,255,255,255,255,255],
 [255,255,255,255,255,255,255,0,0,0,255,255,0,0,255,255,255,255,255,255],
 [255,255,255,255,255,255,255,0,0,0,255,255,0,0,255,255,255,255,255,255],
 [255,255,255,255,255,255,255,0,0,0,255,255,0,0,255,255,255,255,255,255]])

val_to_check=0
agg_res=[] 
for a in arr:
    groups = groupby(a)
    temp = [[label, sum(1 for _ in group)] for label, group in groups]
    for t in temp:
        if t[0]==val_to_check:
            agg_res.append(t)

res_to_group=[l[1] for l in agg_res]
final_res=Counter(res_to_group)
#or, in list form: 
res_list=map(list,final_res.items())

输出:

[[2, 5], [3, 5], [20, 4]]

或者,如果需要,作为函数:

def find_islands(arr,val):
    agg_res=[] 
    for a in arr:
        groups = groupby(a)
        temp = [[label, sum(1 for _ in group)] for label, group in groups]
        for t in temp:
            if t[0]==val:
                agg_res.append(t)

    res_to_group=[l[1] for l in agg_res]
    final_res=Counter(res_to_group)
    #or, in list form: 
    return map(list,final_res.items())

示例运行:

In[65]: find_islands(arr,255)
Out[65]: [[2, 5], [20, 1], [6, 5], [7, 5]]