gpt4 book ai didi

python - Numpy:找到蒙版边缘的索引

转载 作者:太空狗 更新时间:2023-10-30 02:25:04 25 4
gpt4 key购买 nike

我正在尝试查找屏蔽段的索引。例如:

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 ,但它看起来不像我需要的。

最佳答案

这是一种方法-

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)

sample 运行-

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

关于python - Numpy:找到蒙版边缘的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50465162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com