Numpy:找到面具边缘的凹凸

时间:2018-05-22 10:14:58

标签: python arrays numpy

我试图找到屏蔽段的多余部分。例如:

mask = [1, 0, 0, 1, 1, 1, 0, 0]
segments = [(0, 0), (3, 5)]

目前的解决方案看起来像这样(它的非常慢,因为我的面具包含数百万个数字):

segments = []
start = 0
for i in range(len(mask) - 1):
    e1 = mask[i]
    e2 = mask[i + 1]
    if e1 == 0 and e2 == 1:
        start = i + 1
    elif e1 == 1 and e2 == 0:
        segments.append((start, i))

有没有办法用numpy有效地做到这一点?

我唯一设法谷歌的是numpy.ma.notmasked_edges,但它看起来并不像我需要的那样。

2 个答案:

答案 0 :(得分:4)

这是一种方法 -

def start_stop(a, trigger_val):
    # "Enclose" mask with sentients to catch shifts later on
    mask = np.r_[False,np.equal(a, trigger_val),False]

    # Get the shifting indices
    idx = np.flatnonzero(mask[1:] != mask[:-1])

    # Get the start and end indices with slicing along the shifting ones
    return zip(idx[::2], idx[1::2]-1)

示例运行 -

In [216]: mask = [1, 0, 0, 1, 1, 1, 0, 0]

In [217]: start_stop(mask, trigger_val=1)
Out[217]: [(0, 0), (3, 5)]

使用它来获取0s -

的边缘
In [218]: start_stop(mask, trigger_val=0)
Out[218]: [(1, 2), (6, 7)]

100000x上的计时加大了数据量 -

In [226]: mask = [1, 0, 0, 1, 1, 1, 0, 0]

In [227]: mask = np.repeat(mask,100000)

# Original soln
In [230]: %%timeit
     ...: segments = []
     ...: start = 0
     ...: for i in range(len(mask) - 1):
     ...:     e1 = mask[i]
     ...:     e2 = mask[i + 1]
     ...:     if e1 == 0 and e2 == 1:
     ...:         start = i + 1
     ...:     elif e1 == 1 and e2 == 0:
     ...:         segments.append((start, i))
1 loop, best of 3: 401 ms per loop

# @Yakym Pirozhenko's soln
In [231]: %%timeit
     ...: slices = np.ma.clump_masked(np.ma.masked_where(mask, mask))
     ...: result = [(s.start, s.stop - 1) for s in slices]
100 loops, best of 3: 4.8 ms per loop

In [232]: %timeit start_stop(mask, trigger_val=1)
1000 loops, best of 3: 1.41 ms per loop

答案 1 :(得分:2)

使用np.ma.clump_masked的替代方法。

mask = np.array([1, 0, 0, 1, 1, 1, 0, 0])
# get a list of "clumps" or contiguous slices.
slices = np.ma.clump_masked(np.ma.masked_where(mask, mask))
# convert each slice to a tuple of indices.
result = [(s.start, s.stop - 1) for s in slices]
# [(0, 0), (3, 5)]