Skip to main content
 首页 » 编程设计

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

2024年09月07日15mq0036

对于给定的数组(如下所示)和给定的值(此处为 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] 因为可以在第二行和第四行以及第二/第三列之间识别出五个 0 的第一个“模式”。存在只有一个 0 的第二个模式。

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

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

请您参考如下方法:

您要查找的是数组中的“连通分量”。为此,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]