使用 Scipy 查找幅度大于 0 的所有峰值
先决条件: Mathplotlib , Scipy
在本文中,我们将看到如何借助 find_peaks()函数找到 0 以上的所有“x”点,该函数采用一维数组并通过相邻值的简单比较找到所有局部最大值。
方法:
- 导入所需的模块。
- 根据 find_peaks() 属性查找信号内的峰值。
- 标记图形。
- 显示图表。
第 1 步:导入所有库。
Python3
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import find_peaks
from scipy import signal
Python3
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import find_peaks
from scipy import signal
t = np.linspace(0, 1, 500, endpoint=False)
sig = np.sin(2 * np.pi * t)
x= signal.square(2 * np.pi * 30 * t, duty=(sig + 1)/2)
peak, _ = find_peaks(x, height=0)
Python3
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import find_peaks
from scipy import signal
t = np.linspace(0, 1, 500, endpoint=False)
sig = np.sin(2 * np.pi * t)
x= signal.square(2 * np.pi * 30 * t, duty=(sig + 1)/2)
peak, _ = find_peaks(x, height=0)
plt.plot(x)
plt.title("Find peaks inside a signal - Geeksforgeeks")
plt.plot(peak, x[peak], "x", color = 'r')
plt.plot(np.zeros_like(x), "--", color="black")
plt.show()
第 2 步: electrocardiogram():返回的信号是 5 分钟长的心电图 (ECG),这是心脏电活动的医学记录,以 360 Hz 采样。
Syntax:
scipy.signal.find_peaks(x, height=None)
Parameter:
- x: A signal with peaks.
- height: Required height of peaks. Either a number, None,
Return:
peaks: Indices of peaks in x that satisfy all given conditions.
peak_heights: If the height is given, the height of each peak is x.
蟒蛇3
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import find_peaks
from scipy import signal
t = np.linspace(0, 1, 500, endpoint=False)
sig = np.sin(2 * np.pi * t)
x= signal.square(2 * np.pi * 30 * t, duty=(sig + 1)/2)
peak, _ = find_peaks(x, height=0)
以下是完整的实现:
蟒蛇3
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import find_peaks
from scipy import signal
t = np.linspace(0, 1, 500, endpoint=False)
sig = np.sin(2 * np.pi * t)
x= signal.square(2 * np.pi * 30 * t, duty=(sig + 1)/2)
peak, _ = find_peaks(x, height=0)
plt.plot(x)
plt.title("Find peaks inside a signal - Geeksforgeeks")
plt.plot(peak, x[peak], "x", color = 'r')
plt.plot(np.zeros_like(x), "--", color="black")
plt.show()
输出: