我在Python中实现了一个峰值检测算法,它只检测那些超过阈值大小的峰值。我也不想用硬件来扩展这个功能。在
from math import sin,isnan
from pylab import *
def peakdet(v, delta,thresh,x):
delta=abs(delta)
maxtab = []
mintab = []
v = asarray(v)
mn, mx = v[0], v[0]
mnpos, mxpos = NaN, NaN
lookformax = True
for i in arange(len(v)):
this = v[i]
if abs(this)>thresh:
if this > mx:
mx = this
mxpos = x[i]
if this < mn:
mn = this
mnpos = x[i]
if lookformax:
if (this < mx-delta):
if (mx>abs(thresh)) and not isnan(mxpos):
maxtab.append((mxpos, mx))
mn = this
mnpos = x[i]
lookformax = False
else:
if (this > mn+delta):
if (mn<-abs(thresh)) and not isnan(mnpos):
mintab.append((mnpos, mn))
mx = this
mxpos = x[i]
lookformax = True
return array(maxtab), array(mintab)
#Input Signal
t=array(range(100))
series=0.3*sin(t)+0.7*cos(2*t)-0.5*sin(1.2*t)
thresh=0.95 #Threshold value
delta=0.0 #
a=zeros(len(t)) #
a[:]=thresh #
maxtab, mintab = peakdet(series,delta,thresh,t)
#Plotting output
scatter(array(maxtab)[:,0], array(maxtab)[:,1], color='red')
scatter(array(mintab)[:,0], array(mintab)[:,1], color='blue')
xlim([0,t[-1]])
title('Peak Detector')
grid(True)
plot(t,a,color='green',linestyle='--',dashes=(5,3))
plot(t,-a,color='green',linestyle='--',dashes=(5,3))
annotate('Threshold',xy=(t[-1],thresh),fontsize=9)
plot(t,series,'k')
show()
这个程序的问题是,它无法检测到一些峰值,即使它们高于阈值。 这是我得到的输出:
我看到了其他有峰值检测问题的帖子,但找不到任何解决方案。请帮助并建议更正。在
你的函数使用了很多参数。您可以将问题分解为几个步骤:
maxthresh
和minthresh
列表中。在maxthresh
列表,如果点之前的y值小于该点,而该点之后的y值小于该点,则该点为峰值。在minthresh
列表,如果点之前的y值大于该点,并且该点之后的y值大于该点,则该点为峰值。在代码实现:
测试代码:
^{pr2}$额外测试,以确保在多个点超过阈值时检测到峰值:
因此,这里有一个numpythonic解决方案(这比显式地执行循环要好得多)。在
我使用roll函数来移动位置上的数字+1或-1。“峰值”也被定义为局部最大值,其中前一个和后一个数小于中心值。在
完整代码是:
如果你画出来,你会得到:
这些代码
只在这种情况下运行
^{pr2}$所以你只能在阈值上的下一个点比它小的时候找到一个峰值。在
把它放出来
相关问题 更多 >
编程相关推荐