File size: 2,641 Bytes
35f60b9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | import os
import numpy as np
from scipy.signal import butter, sosfilt, lfilter, iirnotch
from scipy.signal import find_peaks
def butter_bandpass(lowcut, highcut, fs, order=8):
low = lowcut
high = highcut
sos = butter(order, [low, high], btype='band', fs=fs, output='sos', analog=False)
return sos
def butter_highpass(lowcut, fs, order=8):
low = lowcut
sos = butter(order, low, btype='highpass', fs=fs, output='sos', analog=False)
return sos
def butter_lowpass(highcut, fs, order=8):
high = highcut
sos = butter(order, high, btype='lowpass', fs=fs, output='sos', analog=False)
return sos
def butter_bandpass_filter(data, lowcut, highcut, fs, order=8):
if highcut > fs/2:
sos = butter_highpass(lowcut, fs, order=order)
elif lowcut <= 0:
sos = butter_lowpass(highcut, fs, order=order)
else:
sos = butter_bandpass(lowcut, highcut, fs, order=order)
#y = lfilter(b, a, data)
y = sosfilt(sos, data)
return y
def correct_ecg_inversion(ecg_signal, sampling_rate):
"""
ECG ์ ํธ๊ฐ ๋ค์งํ๋์ง ๊ฐ์งํ๊ณ ์ฌ๋ฐ๋ฅด๊ฒ ์์ ํฉ๋๋ค.
Args:
ecg_signal (np.array): ECG ์ ํธ ๋ฐ์ดํฐ.
sampling_rate (int): ์ํ๋ง ์ฃผํ์ (Hz).
Returns:
np.array: ์์ ๋ ECG ์ ํธ.
bool: ๋ค์งํ์ด ๊ฐ์ง๋์๋์ง ์ฌ๋ถ.
"""
# QRS๊ตฐ์ Rํ๋ฅผ ์ฐพ๊ธฐ ์ํด ์ ํธ์ ์์ ํผํฌ๋ฅผ ์ฐพ์
# prominence: ํผํฌ๊ฐ ์ฃผ๋ณ๋ณด๋ค ์ผ๋ง๋ ํ์ด๋์๋์ง, distance: ํผํฌ ๊ฐ ์ต์ ๊ฑฐ๋ฆฌ
positive_peaks, _ = find_peaks(ecg_signal, prominence=0.1, distance=0.3 * sampling_rate)
# QRS๊ตฐ์ Sํ(๋ค์งํ Rํ)๋ฅผ ์ฐพ๊ธฐ ์ํด ์ ํธ๋ฅผ ๋ค์ง์ด์ ํผํฌ๋ฅผ ์ฐพ์
negative_peaks, _ = find_peaks(-ecg_signal, prominence=0.1, distance=0.3 * sampling_rate)
# ํผํฌ๊ฐ ํ๋๋ ๊ฐ์ง๋์ง ์์ผ๋ฉด ์๋ณธ ์ ํธ ๋ฐํ
if len(positive_peaks) == 0 and len(negative_peaks) == 0:
return ecg_signal, False
# ์์ ํผํฌ์ ์์ ํผํฌ์ ํ๊ท ์งํญ ๊ณ์ฐ
mean_pos_amp = np.mean(ecg_signal[positive_peaks]) if len(positive_peaks) > 0 else 0
mean_neg_amp = np.mean(ecg_signal[negative_peaks]) if len(negative_peaks) > 0 else 0
# ๋ง์ฝ ์์ ํผํฌ์ ์ ๋๊ฐ์ด ์์ ํผํฌ๋ณด๋ค ํฌ๋ฉด ๋ค์งํ ๊ฒ์ผ๋ก ํ๋จ
is_inverted = abs(mean_neg_amp) > abs(mean_pos_amp)
if is_inverted:
# print("๐ก ECG ์ ํธ๊ฐ ๋ค์งํ ๊ฒ์ ๊ฐ์งํ์ฌ ์์ ํฉ๋๋ค.")
return ecg_signal * -1, True
else:
# print("โ
ECG ์ ํธ๊ฐ ์ ์ ๋ฐฉํฅ์
๋๋ค.")
return ecg_signal, False |