def peaks_hr(sig, peak_inds, fs, title, figsize=(20,10), saveto=None): #这个函数是用来画出信号峰值和心律 #计算心律 hrs=processing.compute_hr(sig_len=sig.shape[0], qrs_inds=peak_inds, fs=fs) N=sig.shape[0] fig, ax_left=plt.subplots(figsize=figsize) ax_right=ax_left.twinx() ax_left.plot(sig, color='#3979f0', label='Signal') ax_left.plot(peak_inds, sig[peak_inds], 'rx', marker='x', color='#8b0000', label='Peak', markersize=12)#画出标记 ax_right.plot(np.arange(N), hrs, label='Heart rate', color='m', linewidth=2)#画出心律,y轴在右边 ax_left.set_title(title) ax_left.set_xlabel('Time (ms)') ax_left.set_ylabel('ECG (mV)', color='#3979f0') ax_right.set_ylabel('Heart rate (bpm)', color='m') #设置颜色使得和线条颜色一致 ax_left.tick_params('y', colors='#3979f0') ax_right.tick_params('y', colors='m') if saveto is not None: plt.savefig(saveto, dpi=600) plt.show()
def filter_ecg(ecg, fs, get_heart_rate=False, cutoff_frequencies=[0.5, 100.0]): nyq_f = fs / 2 w_low = cutoff_frequencies[0] / (math.pi * nyq_f) w_high = cutoff_frequencies[1] / (math.pi * nyq_f) filt_order = 4 b, a = scipy.signal.butter(filt_order, [w_low, w_high], btype='bandpass') processed_ecg = scipy.signal.filtfilt(b, a, ecg) if get_heart_rate: qrs_inds = processing.gqrs_detect(sig=ecg, fs=fs) hr = processing.compute_hr(sig_len=len(ecg), qrs_inds=qrs_inds, fs=fs) return (processed_ecg, hr) else: return (processed_ecg)
def calculateHeartRate(sample_to, xqrs, fs): ''' Calculates the heart rate of signal uptil the point specified Args: sample_to (int): end sample of signal xqrs (signal): used for qrs detection fs (int): frequency of signal Returns: heart_rate (int): heart beat of person ''' heart_rate_list = processing.compute_hr(sample_to, xqrs.qrs_inds, fs) heart_rate = heart_rate_list[-1] return heart_rate
def peaks_hr(sig, peak_inds, fs, title, figsize=(20, 10), saveto=None): "Plot a signal with its peaks and heart rate" # Calculate heart rate hrs = processing.compute_hr(sig_len=sig.shape[0], qrs_inds=peak_inds, fs=fs) N = sig.shape[0] fig, ax_left = plt.subplots(figsize=figsize) ax_right = ax_left.twinx() ax_left.plot(sig, color='#3979f0', label='Signal') ax_left.plot(peak_inds, sig[peak_inds], 'rx', marker='x', color='#8b0000', label='Peak', markersize=12) ax_right.plot(np.arange(N), hrs, label='Heart rate', color='m', linewidth=2) ax_left.set_title(title) ax_left.set_xlabel('Time (ms)') ax_left.set_ylabel('ECG (mV)', color='#3979f0') ax_right.set_ylabel('Heart rate (bpm)', color='m') # Make the y-axis label, ticks and tick labels match the line color. ax_left.tick_params('y', colors='#3979f0') ax_right.tick_params('y', colors='m') if saveto is not None: plt.savefig(saveto, dpi=600) plt.show()
import imutils import time import dlib import cv2 # 1. Read signal record = wfdb.rdrecord('mit-bih-arrhythmia-database-1.0.0/108', channels=[0]) # 2. Detect QRS locations qrs_locs = processing.gqrs_detect(record.p_signal[:, 0], fs=record.fs) # 5. Length of signal len = record.sig_len # 6. Compute heart rate heart_rate = processing.compute_hr(len, qrs_locs, fs=record.fs) # 7. Remove Nan values from array heart_rate = heart_rate[~np.isnan(heart_rate)] # 8. Calculate RR from heart rate # RR-interval is shorter and wider for awake subject than drowsy subject. RR = 60 / heart_rate # From hrv analysis get frequency features dict = hrvanalysis.extract_features.get_frequency_domain_features(RR) itr = 0 length = RR.size - 1000
def ExtractFeatures(dataset, size, minThreshold): # Features qAmplitudes = [] rAmplitudes = [] qrsDurations = [] rrIntervals = [] heartRatesDuringHeartBeat = [] minSize = sys.maxsize signals = dataset['signal'] labels = dataset['label'] for i, sig in enumerate(signals[:size]): print(str(i) + "/" + str(len(signals)) + " ...") qrsInds = processing.gqrs_detect(sig=sig.astype('float64'), fs=300) heartRates = processing.compute_hr(sig_len=sig.shape[0], fs=300, qrs_inds=sorted(qrsInds)) rPoints, sPoints, qPoints = QRS_util.ECG_QRS_detect( sig, 300, True, False) lenHb = sys.maxsize lenSigQrs = sys.maxsize lenHr = sys.maxsize lenQ = sys.maxsize lenR = sys.maxsize if (len(heartRates) > 0 and len(rPoints) > 0): # Adding features for each signal. heartRatesDuringHeartBeat.append(np.array(heartRates[rPoints])) lenHr = len(heartRates[rPoints]) if (len(qPoints) > 0): qAmplitudes.append(np.array(sig[qPoints])) lenQ = len(sig[qPoints]) if (len(rPoints) > 0): rAmplitudes.append(np.array(sig[rPoints])) lenR = len(sig[rPoints]) if (len(qPoints) > 0 and len(rPoints) > 0): sigQrsDuration = [ sPoints[i] - qPoints[i] for i in range(len(qPoints) - 1) ] qrsDurations.append(np.array(sigQrsDuration)) lenSigQrs = len(sigQrsDuration) hbIntervals = [ rPoints[i + 1] - rPoints[i] for i in range(len(rPoints) - 1) ] rrIntervals.append(np.array(hbIntervals)) lenHb = len(hbIntervals) minIter = min(lenHb, lenQ, lenR, lenSigQrs, lenHr) if minIter < minThreshold: # Rollback del heartRatesDuringHeartBeat[-1] del qAmplitudes[-1] del rAmplitudes[-1] del qrsDurations[-1] del rrIntervals[-1] elif minIter < minSize: minSize = minIter qAmplitudes = np.array( [np.array(x[:minSize], dtype='int64') for x in qAmplitudes]) rAmplitudes = np.array( [np.array(x[:minSize], dtype='int64') for x in rAmplitudes]) rrIntervals = np.array( [np.array(x[:minSize], dtype='int64') for x in rrIntervals]) qrsDurations = np.array( [np.array(x[:minSize], dtype='int64') for x in qrsDurations]) heartRatesDuringHeartBeat = np.array([ np.array(x[:minSize], dtype='int64') for x in heartRatesDuringHeartBeat ]) qAmplitudes = np.stack(qAmplitudes, axis=0) rAmplitudes = np.stack(rAmplitudes, axis=0) heartRatesDuringHeartBeat = np.stack(heartRatesDuringHeartBeat, axis=0) rrIntervals = np.stack(rrIntervals, axis=0) qrsDurations = np.stack(qrsDurations, axis=0) return qAmplitudes, rAmplitudes, heartRatesDuringHeartBeat, rrIntervals, qrsDurations, labels[: size], minSize