Skip to main content
 首页 » 编程设计

python之区域边界的 Numpy 检测

2024年11月01日7cloudgamer

给定一个一维值数组:

A = [x,..,x,0,..,0,x,..,x,0,..,0,x,..,x,......]

哪里:

x,..,x代表任意数量的任意Value

和

0,..,0代表任意数量的零

我需要找到一个快速的算法来找到边界的索引 即:..,x,0,.. 和 ..,0,x..

这个问题似乎适合并行化,但这超出了我的经验,简单的遍历数组会因为数据太大而变慢

谢谢 马丁

请您参考如下方法:

@chthonicdaemon 的回答让您完成了 90% 的工作,但如果您真的想使用索引来分割数组,则需要一些额外的信息。

大概,您想使用索引来提取数组中不为 0 的区域。您已经找到了数组更改的索引,但您不知道更改是否来自 True 到 False 或相反的方式。因此,您需要检查第一个和最后一个值并进行相应调整。否则,在某些情况下,您最终会提取零段而不是数据。

例如:

import numpy as np 
 
def contiguous_regions(condition): 
    """Finds contiguous True regions of the 1D boolean array "condition". 
    Returns a 2D array where the first column is the start index of the region 
    and the second column is the end index.""" 
    # Find the indicies of changes in "condition" 
    idx = np.flatnonzero(np.diff(condition)) + 1 
 
    # Prepend or append the start or end indicies to "idx" 
    # if there's a block of "True"'s at the start or end... 
    if condition[0]: 
        idx = np.append(0, idx) 
    if condition[-1]: 
        idx = np.append(idx, len(condition)) 
 
    return idx.reshape(-1, 2) 
 
# Generate an example dataset... 
t = np.linspace(0, 4*np.pi, 20) 
x = np.abs(np.sin(t)) + 0.1 
x[np.sin(t) < 0.5] = 0 
 
print x 
 
# Get the contiguous regions where x is not 0 
for start, stop in contiguous_regions(x != 0): 
    print x[start:stop] 

所以在这种情况下,我们的示例数据集如下所示:

array([ 0.        ,  0.71421271,  1.06940027,  1.01577333,  0.        , 
        0.        ,  0.        ,  0.        ,  0.        ,  0.        , 
        0.        ,  0.93716648,  1.09658449,  0.83572391,  0.        , 
        0.        ,  0.        ,  0.        ,  0.        ,  0.        ]) 

通过做:

for start, stop in contiguous_regions(x != 0): 
    print x[start:stop] 

我们会得到:

[ 0.71421271  1.06940027  1.01577333] 
[ 0.93716648  1.09658449  0.83572391]