numpy 数组中给定值的凸包 - python 2.7

Convex Hull of a given value inside an numpy array - python 2.7

对于给定的数组(如下所示)和给定的值(此处为 0),我想计算在同一个凸包上可以关联多少个 0。

数组:

1 2 4 5 8 9 7
4 0 0 7 5 6 8
6 5 0 4 3 5 2
1 0 0 5 7 0 6
2 3 5 7 8 9 4

对于建议的数组,解决方案应为:[5, 1],因为可以在第二行和第四行以及 second/third 列之间识别出五个 0 中的第一个 "pattern"。存在只有一个 0 的第二个模式。

你知道如何得到它吗?我知道如何计算 0 的个数。也许我可以用 numpy 数组的掩码选项做点什么?

致以最诚挚的问候,感谢您的帮助,

您要查找的是数组中的 "connected components"。 Scipy 有一个方便的 label 功能:

import numpy as np
from scipy.ndimage.measurements import label

a = np.array([
    [1, 2, 4, 5, 8, 9, 7],
    [4, 0, 0, 7, 5, 6, 8],
    [6, 5, 0, 4, 3, 5, 2],
    [1, 0, 0, 5, 7, 0, 6],
    [2, 3, 5, 7, 8, 9, 4],])

labs, n_components = label(a==0)

component_sizes = [np.sum(labs==i) for i in range(1, n_components+1)]

print(component_sizes)

打印 [5, 1]