二维 numpy 数组中的簇大小?

Cluster sizes in 2D numpy array?

我有一个与已经回答的问题类似的问题 before,只是稍作修改: 我有一个值为 -1,0,1 的二维 numpy 数组。我想找到值为 1 或 -1(分别)的元素的簇大小。你对如何做到这一点有什么建议吗? 谢谢!

您是否要计算二维数组中存在的 1 或 -1 的数量?

如果是这样,那就很容易了。说 ar = np.array([1, -1, 1, 0, -1])

如果是,

 n_1 = sum([1 for each in ar if each==1]);
 n_m1 = sum([1 for each in ar if each==-1]) 

这是我的解决方案:

import numpy as np
import copy

arr = np.array([[1,1,-1,0,1],[1,1,0,1,1],[0,1,0,1,0],[-1,-1,1,0,1]])
print(arr)
col, row = arr.shape
mask_ = np.ma.make_mask(np.ones((col,row)))

cluster_size = {}

def find_neighbor(arr, mask, col_index, row_index):
    index_holder = []

    col, row = arr.shape
    left = (col_index, row_index-1)
    right = (col_index,row_index+1)
    top = (col_index-1,row_index)
    bottom = (col_index+1,row_index)

    left_ = row_index-1>=0
    right_ = (row_index+1)<row
    top_ = (col_index-1)>=0
    bottom_ = (col_index+1)<col

    #print(list(zip([left,right,top,bottom],[left_,right_,top_,bottom_])))
    for each in zip([left,right,top,bottom],[left_,right_,top_,bottom_]):
        if each[-1]:
            if arr[col_index,row_index]==arr[each[0][0],each[0][1]] and mask[each[0][0],each[0][1]]:
                mask[each[0][0],each[0][1]] = False
                index_holder.append(each[0])

    return mask,index_holder

for i in range(col):
    for j in range(row):
        if mask_[i,j] == False:
            pass
        else:
            value = arr[i,j]
            mask_[i,j] = False
            index_to_check = [(i,j)]
            kk=1
            while len(index_to_check)!=0:
                index_to_check_deepcopy = copy.deepcopy(index_to_check)
                for each in index_to_check:
                    mask_, temp_index = find_neighbor(arr,mask_,each[0],each[1])
                    index_to_check = index_to_check + temp_index
                    # print("check",each,temp_index,index_to_check)
                    kk+=len(temp_index)
                for each in index_to_check_deepcopy:
                    del(index_to_check[index_to_check.index(each)])
            if (value,kk) in cluster_size:
                cluster_size[(value,kk)] = cluster_size[(value,kk)] + 1
            else:
                cluster_size[(value,kk)] = 1
print(cluster_size)

cluster_size是一个字典,key是一个二元组(a,b),a给出簇的值(这就是你要解决的,对吧),b给出的计数那个值。每个键的值是簇数。