neuropsychology / NeuroKit

NeuroKit2: The Python Toolbox for Neurophysiological Signal Processing
https://neuropsychology.github.io/NeuroKit
MIT License
1.53k stars 410 forks source link

why always miss the first R peak while using the "ecg_findpeaks" function #937

Open zdjk104tan opened 9 months ago

zdjk104tan commented 9 months ago

As the title, I always miss the first R peak while using the "ecg_findpeaks" function to deal the windows ECG. I'm very thank, if someone can help me. Figure_1 Figure_2 Figure_3 Figure_4 Figure_5 Figure_6 Figure_7 Figure_8

welcome[bot] commented 9 months ago

Hi 👋 Thanks for reaching out and opening your first issue here! We'll try to come back to you as soon as possible. ❤️ kenobi

DominiqueMakowski commented 9 months ago

It probably has to do with the algorithm. You can try with a different peak detection method

zdjk104tan commented 9 months ago

def find_r_peaks(signal): r_peaks_dict = nk.ecg_findpeaks(signal, sampling_rate=256,method="neurokit")

获取R波峰值和对应的索引位置

r_peaks = r_peaks_dict["ECG_R_Peaks"]
r_waveform = signal[r_peaks]
r_peak_values = r_waveform

# 绘制心电图及检测的R波位置
plt.figure(figsize=(12, 6))
plt.plot(signal, label='Normalized ECG Signal')
plt.plot(r_peaks, r_peak_values, 'r*', label='Detected R-peaks')
plt.xlabel('Sample Index')
plt.ylabel('Amplitude')
plt.title('ECG Signal with Detected R-peaks using Neurokit2')
plt.legend()
plt.grid(True)
plt.show()
return r_peaks, r_peak_values

"""""""" """"""""

生成心电数据的循环

num_images = 1 # 要生成的图像数量

window_size = 5 # 窗口大小,单位秒 overlap = 1 # 重叠时间,单位秒 duration = 60 # 总时长,单位秒 counter = 0 # 初始化计数器

初始化一个空列表来存储每个窗口的特征

all_windows_features = []

用于存储所有特征的DataFrame

features_df = pd.DataFrame()

for i in tqdm(range(num_images), desc="Generating Images"): ecg = nk.ecg_simulate(duration=duration, sampling_rate=sampling_rate, random_state=i) ecg_cleaned = preprocess_ecg(ecg)

for j in range(0, duration, window_size - overlap):
    # 窗口切割
    start = j * sampling_rate
    end = min((j + window_size) * sampling_rate, len(ecg_cleaned))
    window_signal = ecg_cleaned[start:end]

    # 如果最后一个窗口数据不足,则进行填充
    if len(window_signal) < window_size * sampling_rate:
        window_signal = np.append(window_signal, ecg_cleaned[start - sampling_rate: start])

    r_peaks, r_peak_values = find_r_peaks(window_signal)
zdjk104tan commented 9 months ago

这可能与算法有关。您可以尝试使用不同的峰值检测方法

I use the neurokit method, it seems to have some issues with the heartbeat detection of windowed ECG signals:

r_peaks_dict = nk.ecg_findpeaks(signal, sampling_rate=256,method="neurokit")

LucaCerina commented 8 months ago

The neurokit method smooths the ECG's gradient. There are the smoothwindow and avgwindow keywords to control that. Changing those to a lower value should solve the problem, otherwise try padding the start of the signal with zeros.