12

在 numpy 中,我想检测信号从(以前)低于某个阈值到高于某个其他阈值的点。这适用于去抖,或在存在噪声的情况下准确的过零等。

像这样:

import numpy

# set up little test problem
N = 1000
values = numpy.sin(numpy.linspace(0, 20, N))
values += 0.4 * numpy.random.random(N) - 0.2
v_high = 0.3
v_low = -0.3

# find transitions from below v_low to above v_high    
transitions = numpy.zeros_like(values, dtype=numpy.bool)

state = "high"

for i in range(N):
    if values[i] > v_high:
        # previous state was low, this is a low-to-high transition
        if state == "low":
            transitions[i] = True
        state = "high"
    if values[i] < v_low:
        state = "low"

我想要一种无需显式循环遍历数组的方法:但我想不出任何方法,因为每个状态值都取决于前一个状态。没有循环可以吗?

4

2 回答 2

16

这可以这样做:

def hyst(x, th_lo, th_hi, initial = False):
    hi = x >= th_hi
    lo_or_hi = (x <= th_lo) | hi
    ind = np.nonzero(lo_or_hi)[0]
    if not ind.size: # prevent index error if ind is empty
        return np.zeros_like(x, dtype=bool) | initial
    cnt = np.cumsum(lo_or_hi) # from 0 to len(x)
    return np.where(cnt, hi[ind[cnt-1]], initial)

解释:ind是信号低于下限或高于上限阈值的所有样本的索引,因此“开关”的位置是明确定义的。使用cumsum,您可以创建某种计数器,该计数器指向最后一个定义明确的样本的索引。如果输入向量的起点在两个阈值之间,则为cnt0,因此需要使用该where函数将相应的输出设置为初始值。

信用:这是我在某个 Matlab 论坛上的一篇旧帖子中发现的一个技巧,我将其翻译为 Numpy。这段代码有点难理解,还需要分配各种中间数组。如果 Numpy 包含一个专用函数会更好,类似于您的简单 for 循环,但在 C 中实现以提高速度。

快速测试:

x = np.linspace(0,20, 1000)
y = np.sin(x)
h1 = hyst(y, -0.5, 0.5)
h2 = hyst(y, -0.5, 0.5, True)
plt.plot(x, y, x, -0.5 + h1, x, -0.5 + h2)
plt.legend(('input', 'output, start=0', 'output, start=1'))
plt.title('Thresholding with hysteresis')
plt.show()

结果: 在此处输入图像描述

于 2014-04-25T11:23:08.583 回答
2

我必须对我的工作进行修改,所有这些都基于Bas Swinckels的上述答案,以允许在使用标准阈值和反向阈值时检测阈值交叉。

我对艰难的命名不满意,也许现在应该改为th_hi2loandth_lo2hi而不是th_loand th_hi?使用原始值,行为同样艰难。

def hyst(x, th_lo, th_hi, initial = False):
    """
    x : Numpy Array
        Series to apply hysteresis to.
    th_lo : float or int
        Below this threshold the value of hyst will be False (0).
    th_hi : float or int
        Above this threshold the value of hyst will be True (1).
    """        

    if th_lo > th_hi: # If thresholds are reversed, x must be reversed as well
        x = x[::-1]
        th_lo, th_hi = th_hi, th_lo
        rev = True
    else:
        rev = False

    hi = x >= th_hi
    lo_or_hi = (x <= th_lo) | hi

    ind = np.nonzero(lo_or_hi)[0]  # Index für alle darunter oder darüber
    if not ind.size:  # prevent index error if ind is empty
        x_hyst = np.zeros_like(x, dtype=bool) | initial
    else:
        cnt = np.cumsum(lo_or_hi)  # from 0 to len(x)
        x_hyst = np.where(cnt, hi[ind[cnt-1]], initial)

    if rev:
        x_hyst = x_hyst[::-1]

    return x_hyst

和上面的代码测试,看看它做了什么:

x = np.linspace(0,20, 1000)
y = np.sin(x)
h1 = hyst(y, -0.2, 0.2)
h2 = hyst(y, +0.5, -0.5)
plt.plot(x, y, x, -0.2 + h1*0.4, x, -0.5 + h2)
plt.legend(('input', 'output, classic, hyst(y, -0.2, +0.2)', 
            'output, reversed, hyst(y, +0.5, -0.5)'))
plt.title('Thresholding with hysteresis')
plt.show()

具有两种不同滞后设置的正弦波。

于 2018-02-22T00:22:01.037 回答