demand
Knowing a curve (x, y), I want to find each peak or dip, and the corresponding x value.
Application: Given a spectrogram, it is required to find each peak and corresponding frequency
solution
1. Direct use of existing methods
scipy.signal.find_peaks
2. Write a method by yourself
. Idea: 1. Use sort (list (zip (y, x))) to sort all; 2. Then filter out the results according to various conditions, such as y value, the distance between adjacent peaks, etc. In this way, it may be the same as the idea of Method 1. Therefore, the existing method 1 is directly used first.
plan 1
Direct use method: scipy.signal.find_peaks.
Method description:
scipy.signal.find_peaks(x, height=None,
threshold=None, distance=None, prominence=None, width=None, wlen=None,
rel_height=0.5, plateau_size=None)
Input
- x: data
- Other parameters: various screening conditions. The method will filter the peak based on these filter conditions. See the official documentation for the meaning of each input parameter
Output:
- peaks: ndarray, index id of peaks found
- properties: dict, contains various information of the found peaks, such as properties ['peak_heights']
Examples
from scipy.signal import find_peaks
# 已导入需要处理的数据(x,y)
plt.plot(x,y)
plt.xlabel('freq/Hz')
plt.ylabel('amp')
peak_id,peak_property = find_peaks(y, height=2000, distance=20)
peak_freq = x[peak_id]
peak_height = peak_property['peak_heights']
print('peak_freq',peak_freq)
print('peak_height',peak_height)
Output result: correct.
peak_freq [1.2125e+08 3.0000e+08 4.2125e+08]
peak_height [9277.83035228 4566.30860382 4744.32457053]