MIT心电信号数据p波检测python代码
时间: 2023-06-13 20:02:46 浏览: 122
心电信号检测算法
以下是使用Python进行MIT心电信号的P波检测的代码:
首先,需要安装wfdb包,可以使用以下命令进行安装:
```
!pip install wfdb
```
然后,可以使用以下代码读取MIT心电信号数据:
```
import wfdb
record = wfdb.rdrecord('mitdb/100', channels=[0])
signal = record.p_signal.flatten()
```
接下来,我们需要对信号进行滤波,可以使用以下代码进行带通滤波:
```
from scipy.signal import butter, filtfilt
def butter_bandpass(lowcut, highcut, fs, order=5):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
b, a = butter(order, [low, high], btype='band')
return b, a
def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
y = filtfilt(b, a, data)
return y
fs = record.fs
signal_filtered = butter_bandpass_filter(signal, 1, 30, fs, order=4)
```
接下来,我们需要找到P波。P波通常是QRS波群之前的第一个正向波峰。可以使用以下代码找到P波:
```
import numpy as np
from scipy.signal import find_peaks
peaks, _ = find_peaks(signal_filtered, distance=int(0.2*fs), height=0.2)
rpeaks, _ = wfdb.processing.gqrs_detect(signal_filtered, fs=fs)
p_peaks = []
for p in peaks:
if p < rpeaks[0]:
p_peaks.append(p)
p_peak = np.min(p_peaks)
```
最后,我们可以将P波的位置可视化:
```
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
fig, ax = plt.subplots()
ax.plot(signal_filtered)
ax.add_patch(Rectangle((p_peak-20, -0.5), 40, 1, alpha=0.2, color='r'))
plt.show()
```
完整的代码如下:
```
import wfdb
from scipy.signal import butter, filtfilt, find_peaks
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
def butter_bandpass(lowcut, highcut, fs, order=5):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
b, a = butter(order, [low, high], btype='band')
return b, a
def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
y = filtfilt(b, a, data)
return y
record = wfdb.rdrecord('mitdb/100', channels=[0])
signal = record.p_signal.flatten()
fs = record.fs
signal_filtered = butter_bandpass_filter(signal, 1, 30, fs, order=4)
peaks, _ = find_peaks(signal_filtered, distance=int(0.2*fs), height=0.2)
rpeaks, _ = wfdb.processing.gqrs_detect(signal_filtered, fs=fs)
p_peaks = []
for p in peaks:
if p < rpeaks[0]:
p_peaks.append(p)
p_peak = np.min(p_peaks)
fig, ax = plt.subplots()
ax.plot(signal_filtered)
ax.add_patch(Rectangle((p_peak-20, -0.5), 40, 1, alpha=0.2, color='r'))
plt.show()
```
阅读全文