python - numpy 2d boolean 数组计数连续真实大小

标签 python numpy boolean flood-fill

我有兴趣找出 boolean 数组中“True”补丁的各个大小。例如在 boolean 矩阵中:

[[1, 0, 0, 0],
 [0, 1, 1, 0],
 [0, 1, 0, 0],
 [0, 1, 0, 0]]

输出将是:

[[1, 0, 0, 0],
 [0, 4, 4, 0],
 [0, 4, 0, 0],
 [0, 4, 0, 0]]

我知道我可以递归地执行此操作,但我也有这样的印象:Python 数组操作大规模时成本高昂,是否有可用的库函数?

最佳答案

这是一个快速而简单的完整解决方案:

import numpy as np
import scipy.ndimage.measurements as mnts

A = np.array([
    [1, 0, 0, 0],
    [0, 1, 1, 0],
    [0, 1, 0, 0],
    [0, 1, 0, 0]
])

# labeled is a version of A with labeled clusters:
#
# [[1 0 0 0]
#  [0 2 2 0]
#  [0 2 0 0]
#  [0 2 0 0]]
#
# clusters holds the number of different clusters: 2
labeled, clusters = mnts.label(A)

# sizes is an array of cluster sizes: [0, 1, 4]
sizes = mnts.sum(A, labeled, index=range(clusters + 1))

# mnts.sum always outputs a float array, so we'll convert sizes to int
sizes = sizes.astype(int)

# get an array with the same shape as labeled and the 
# appropriate values from sizes by indexing one array 
# with the other. See the `numpy` indexing docs for details
labeledBySize = sizes[labeled]

print(labeledBySize)

输出:

[[1 0 0 0]
 [0 4 4 0]
 [0 4 0 0]
 [0 4 0 0]]

上面最棘手的一行是“花哨的”numpy 索引:

labeledBySize = sizes[labeled]

其中一个数组用于索引另一个数组。请参阅numpy indexing docs (section "Index arrays")了解其工作原理的详细信息。

我还编写了上述代码的一个版本作为单个紧凑函数 that you can try out yourself online.它包括一个基于随机数组的测试用例。

关于python - numpy 2d boolean 数组计数连续真实大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49776310/

相关文章:

python - 如何生成 3 个字符前缀的唯一列表

python - 将空白字符串替换为 nan

python pandas将数据框展平为列表

Python - 如何将整个 numpy 数组一次全部放入 Queue.Queue 但分别检索每一行

python - 跨数组切片向量化 numpy 均值

c - 数组 boolean 值如何将 Char 条目与 true 或 false 相关联?

Python动态命令行参数

python - 在给定股票列表的循环中创建不同的数据框

javascript - 如何将 Razor boolean 变量传递给 Angular 指令?

java - 我正在尝试迭代数组列表,找到数组中 boolean 值为 false 的第一项,将其设置为 true 并返回它