Skip to main content
 首页 » 编程设计

python之区分作为峰值一部分的局部最大值和峰值的绝对最大值

2025年05月04日15kenshinobiy

我从 mp3 的 10 秒剪辑中获取了振幅数据。然后我对其执行快速傅里叶变换以获取频域中剪辑的数据(如第一张图所示)。我现在想确定峰值所在的频率。

我首先对数据进行平滑处理,这可以在下面的蓝色和红色图中看到。我创建了一个阈值,峰值必须超过才能被考虑。这是下面第三个图上的水平蓝线。可以看出,我的峰值检测代码在一定程度上起作用了。

我现在遇到的问题在下面显示的最终情节中很明显。我的代码正在寻找作为整体峰值一部分的局部最大值的最大值。我需要一种方法来过滤掉这些局部最大值,以便对于每个峰值,我只得到一个标记。即对于下面显示的峰值,我只希望在绝对峰值处有一个标记,而不是沿途的每个小峰值。

我的峰值检测代码如下所示:

for i, item in enumerate(xavg): #xavg contains all the smoothed data points 
    if xavg[i] > threshold: #points must be above the threshold 
        #if not the first or last point (so index isn't out of range)             
        if (i > 0) and (i < (len(xavg)-1)):  
            #greater than points on either side                 
            if (xavg[i] > xavg[i-1]) and (xavg[i] > xavg[i+1]):   
                max_locations.append(i) 

编辑:我认为我没有足够清楚地说明我的问题。我想找到图中 5 个左右最高尖峰的位置,而不仅仅是整体最高点。我基本上是想通过标记其主频率来为剪辑提供音频指纹。

EDIT2:一些更多的代码来帮助展示我在 FFT 和平滑方面所做的工作:

def movingaverage(interval, window_size): 
    window = np.ones(int(window_size))/float(window_size) 
    return np.convolve(interval, window, 'same') 
 
fft = np.fft.rfft(song) 
xavg = movingaverage(abs(fft), 21) 

请您参考如下方法:

您的值可以划分为交替的超过阈值和低于阈值的区域。当您找到局部最大值时,请跟踪哪个最大值,直到您的值再次降至阈值以下。将“区域”最大值放在一边作为真正的峰值,然后继续下一个超过阈值的区域。像这样的东西:

# Store the true peaks 
peaks = [] 
 
# If you consider the first value a possible local maxima. 
# Otherwise, just initialize max_location to (None, 0) 
if xavg[0] > xavg[1]: 
    max_location = (0, xavg[0]) 
else: 
    max_location = (None,0) # position and value 
 
# Use a slice to skip the first and last items. 
for i, item in enumerate(xavg[1:-1]): 
    if xavg[i] > threshold: 
        if ((xavg[i] > xavg[i-1]) and 
            (xavg[i] > xavg[i+1]) and 
            xavg[i] > max_location[1]): 
            max_location = (i, xavg[i]) 
    else: 
        # If we found a previous largest local maxima, save it as a true 
        # peak, then reset the values until the next time we exceed the threshold 
        if max_location[0] is not None: 
            peaks.append(max_location[0]) 
        max_location = None 
        max_location_value = 0 
 
# Do you consider the last value a possible maximum? 
if xavg[i+1] > xavg[i] and xavg[i+1] > max_location[1]: 
    max_location = (i+1, xavg[i+1]) 
 
# Check one last time if the last point was over threshold. 
if max_location[0] is not None: 
    peaks.append(max_location[0])