-
Notifications
You must be signed in to change notification settings - Fork 15
/
create_ecg_images.py
67 lines (53 loc) · 1.82 KB
/
create_ecg_images.py
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
import os
import glob
import wfdb
import biosppy
import matplotlib.pyplot as plt
def get_records(fol_path):
""" To get file paths """
# There are 3 files for each record
# *.atr is one of them
paths = glob.glob(fol_path)
# Get rid of the extension
paths = [path[:-4] for path in paths]
paths.sort()
return paths
def save_fig(data, filename):
""" Convert signal to Image"""
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
plt.axis('off')
plt.plot(data)
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
# plt.savefig(filename, bbox_inches=extent)
print(filename)
plt.close()
def segmentation(filename):
""" Gets the ECG segment (wave) and saves to image """
# to save images in new folder
folder = '/'.join(filename.replace('1.0.0', 'filter').split('/')[:-1])
filename_new = filename.split('/')[-1]
if not os.path.exists(folder):
os.mkdir(folder)
# reads raw signal (ECG I)
record = wfdb.rdsamp(filename)
# get the first column signal
data = record[0][:,1]
signals = []
count = 1
# apply Christov Segmenter to get separate waves
peaks = biosppy.signals.ecg.christov_segmenter(signal=data, sampling_rate=record['fs'])[0]
for i in (peaks[1:-1]):
diff1 = abs(peaks[count - 1] - i)
diff2 = abs(peaks[count + 1] - i)
x = peaks[count - 1] + diff1//2
y = peaks[count + 1] - diff2//2
signal = data[x:y]
signals.append(signal)
count += 1
# save the first wave as the image
save_fig(signals[0], '/'.join([folder, filename_new]))
if __name__ == '__main__':
records = get_records('path-to-the-directory/ecg-id-database-1.0.0/*/*.atr')
for record in records:
segmentation(record)