有一个bulit-in函数argrelextrema
可以完成此任务:
import numpy as np
from scipy.signal import argrelextrema
a = np.array([1,2,3,4,5,4,3,2,1,2,3,2,1,2,3,4,5,6,5,4,3,2,1])
# determine the indices of the local maxima
max_ind = argrelextrema(a, np.greater)
# get the actual values using these indices
r = a[max_ind] # array([5, 3, 6])
这样就为您提供了所需的输出r
。
从SciPy 1.1版开始,您还可以使用find_peaks。以下是从文档本身获取的两个示例。
使用该height
参数,可以选择高于某个阈值的所有最大值(在此示例中,是所有非负最大值;这在必须处理嘈杂的基线时非常有用;如果要查找最小值,只需将输入乘以通过-1
):
import matplotlib.pyplot as plt
from scipy.misc import electrocardiogram
from scipy.signal import find_peaks
import numpy as np
x = electrocardiogram()[2000:4000]
peaks, _ = find_peaks(x, height=0)
plt.plot(x)
plt.plot(peaks, x[peaks], "x")
plt.plot(np.zeros_like(x), "--", color="gray")
plt.show()
另一个非常有用的参数是distance
,它定义了两个峰之间的最小距离:
peaks, _ = find_peaks(x, distance=150)
# difference between peaks is >= 150
print(np.diff(peaks))
# prints [186 180 177 171 177 169 167 164 158 162 172]
plt.plot(x)
plt.plot(peaks, x[peaks], "x")
plt.show()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句