-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdigitization.py
More file actions
1784 lines (1494 loc) · 69 KB
/
Copy pathdigitization.py
File metadata and controls
1784 lines (1494 loc) · 69 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
digitization.py
===============
Core ECG image-to-signal conversion module.
The public interface is the :class:`ECGImage` class. Instantiate it with
four pre-loaded YOLO models and the path to an ECG image, then call
:meth:`ECGImage.run_full_pipeline` followed by
:meth:`ECGImage.save_signals_as_csv` (or :meth:`ECGImage.save_signals_as_wfdb`).
Module-level helpers
--------------------
plot_image — Quick matplotlib preview of a grayscale array.
shadow_removal — Morphological background subtraction.
line_length — Euclidean distance between two 2-D points.
parse_layout_from_folder — Parse rows/cols/layout flags from a folder name.
"""
import os
os.environ["OPENBLAS_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["MKL_NUM_THREADS"] = "1"
import numpy as np
import cv2
cv2.setNumThreads(0) # disable OpenCV's internal thread pool
import matplotlib.pyplot as plt
from ultralytics import YOLO
from PIL import Image
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score, mean_squared_error
from scipy.interpolate import interp1d
import wfdb
from scipy import signal
from skimage import morphology, segmentation
from scipy.signal import savgol_filter, find_peaks
from scipy.stats import pearsonr
from skimage.filters import threshold_multiotsu
from concurrent.futures import ThreadPoolExecutor
import re
import pandas as pd
import torch
import time
from patched_yolo_infer import (
MakeCropsDetectThem,
CombineDetections,
visualize_results,
)
def plot_image(img, title="Image Plot", size=(12, 12), show_axis=False):
"""Display a grayscale image with matplotlib.
Parameters
----------
img : np.ndarray
Grayscale image array (H × W).
title : str, optional
Figure title (default ``"Image Plot"``).
size : tuple[int, int], optional
Figure size in inches ``(width, height)`` (default ``(12, 12)``).
show_axis : bool, optional
Whether to draw axis ticks (default ``False``).
"""
plt.figure(figsize=size)
plt.imshow(img, cmap='gray')
plt.title(title)
if not show_axis:
plt.axis('off')
plt.show()
def shadow_removal(img):
"""Remove uneven illumination / shadow from a grayscale image.
Uses morphological dilation followed by median blur to estimate the
background, then subtracts it from the original to yield a
normalised, shadow-free image.
Parameters
----------
img : np.ndarray
Grayscale uint8 image.
Returns
-------
np.ndarray
Shadow-corrected uint8 image, intensity range [0, 255].
"""
dilated_img = cv2.dilate(img, np.ones((7, 7), np.uint8))
bg_img = cv2.medianBlur(dilated_img, 15)
diff_img = 255 - cv2.absdiff(img, bg_img)
norm_img = cv2.normalize(diff_img, None, alpha=0, beta=255,
norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8UC1)
return norm_img
def line_length(x1, y1, x2, y2):
"""Return the Euclidean length of a line segment.
Parameters
----------
x1, y1 : float
Coordinates of the first endpoint.
x2, y2 : float
Coordinates of the second endpoint.
Returns
-------
float
Length of the segment in the same units as the inputs.
"""
return np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
def parse_layout_from_folder(folder_path):
"""Parse ECG layout metadata encoded in a folder name.
Expected naming convention::
ecg_signals_<rows>x<cols>_<Rythm|None>_<Cabrera|Normal>
Parameters
----------
folder_path : str
Absolute or relative path whose final component encodes the layout.
Returns
-------
layout_key : tuple[int, int, bool] or None
``(rows, cols, is_cabrera)``. ``None`` if the name does not match.
calibration : bool or None
``True`` when a rhythm (calibration) strip is present, ``None`` on
parse failure.
"""
base_name = folder_path.split('/')[-1]
match = re.search(r'ecg_signals_(\d+)x(\d+)_(None|Rythm)_(Cabrera|Normal)', base_name)
if match:
rows = int(match.group(1))
cols = int(match.group(2))
calibration = (match.group(3) == 'Rythm')
cabrera_flag = (match.group(4) == 'Cabrera')
layout_key = (rows, cols, cabrera_flag)
return layout_key, calibration
else:
return None, None
class ECGImage:
"""End-to-end digitizer for a single 12-lead ECG image.
The class encapsulates every processing stage — from raw pixel
loading to per-lead voltage time-series export. All intermediate
results (masks, bounding boxes, calibration constants, signal grid)
are stored as instance attributes so that individual stages can be
inspected or visualised after the pipeline runs.
Typical usage
-------------
>>> ecg = ECGImage(box_model, seg_model, name_model, pulse_model, "ecg.png")
>>> ecg.run_full_pipeline()
>>> ecg.save_signals_as_csv("record_001", directory="./output")
Parameters
----------
box_model : ultralytics.YOLO
Pre-loaded YOLO model that detects lead bounding boxes.
segmentation_model : str
Path to the YOLO segmentation model checkpoint. Loaded
internally by ``patched_yolo_infer.MakeCropsDetectThem`` so
that it can operate on image patches.
lead_name_model : ultralytics.YOLO
Pre-loaded YOLO model that classifies lead name labels
(I, II, III, aVR, aVL, aVF, V1–V6).
pulse_model : ultralytics.YOLO
Pre-loaded YOLO model that detects calibration pulse boxes.
image_path : str
Path to the ECG image (.png, .jpg, or .jpeg).
wfdb_path : str, optional
Path to a WFDB record (without extension) used for ground-truth
comparison in :meth:`calculate_metrics_ptb`. Not required for
normal digitization.
Attributes set by the pipeline
--------------------------------
image : np.ndarray
Loaded and padded grayscale image.
processed_image : np.ndarray
Shadow-removed, blurred version used for all model inference.
lead_segmentation : list
``CombineDetections`` objects from the three segmentation passes.
mask_image : np.ndarray
Binary mask (H × W, uint8) combining all segmented lead polygons.
row_centers : np.ndarray
Y-pixel positions of detected lead row centres.
roi : tuple[float, float]
``(min_y, max_y)`` bounding the active ECG area.
lead_bboxes : list[list[float]]
``[x1, y1, x2, y2]`` boxes from ``box_model``.
lead_name_bboxes : list[dict]
``{'bbox': [...], 'class_name': str}`` from ``lead_name_model``.
reference_pulses : list[dict]
``{'bbox': [...], 'image': np.ndarray}`` from ``pulse_model``.
volt_per_pixel : float
Calibration constant: millivolts per pixel (vertical axis).
time_per_pixel : float
Calibration constant: seconds per pixel (horizontal axis).
is_cabrera : bool
Whether the ECG uses Cabrera lead ordering.
has_calibration_pulse : bool
Whether a rhythm/calibration strip row is present.
layout : list[list[str]]
2-D grid of lead names matching the detected row/column layout.
grid : list[list[dict]]
Mask grid — each cell contains ``'lead'`` (str) and ``'signal'``
(np.ndarray of the binary mask slice).
signal_grid : list[list[dict]]
After :meth:`extract_signals`: cells additionally contain
``'signal'`` as a list of float mV values.
"""
def __init__(self, box_model, segmentation_model, lead_name_model, pulse_model,
image_path, wfdb_path=""):
self.image_path = image_path # stored for retry in run_full_pipeline
self.load_image(image_path)
self.wfdb_path = wfdb_path
self.box_model = box_model
self.segmentation_model = segmentation_model
self.lead_name_model = lead_name_model
self.pulse_model = pulse_model
self.is_cabrera = None
self.has_calibration_pulse = None
self.standard_layouts = {
# Standard layouts
(12, 1, False): [['I'], ['II'], ['III'], ['aVR'], ['aVL'], ['aVF'],
['V1'], ['V2'], ['V3'], ['V4'], ['V5'], ['V6']],
(6, 2, False): [['I', 'V1'], ['II', 'V2'], ['III', 'V3'],
['aVR', 'V4'], ['aVL', 'V5'], ['aVF', 'V6']],
(4, 3, False): [['I', 'II', 'III'], ['aVR', 'aVL', 'aVF'],
['V1', 'V2', 'V3'], ['V4', 'V5', 'V6']],
(3, 4, False): [['I', 'aVR', 'V1', 'V4'], ['II', 'aVL', 'V2', 'V5'],
['III', 'aVF', 'V3', 'V6']],
# Cabrera layouts
(12, 1, True): [['aVL'], ['I'], ['aVR'], ['II'], ['aVF'], ['III'],
['V1'], ['V2'], ['V3'], ['V4'], ['V5'], ['V6']],
(6, 2, True): [['aVL', 'V1'], ['I', 'V2'], ['aVR', 'V3'],
['II', 'V4'], ['aVF', 'V5'], ['III', 'V6']],
(4, 3, True): [['aVL', 'I', 'aVR'], ['II', 'aVF', 'III'],
['V1', 'V2', 'V3'], ['V4', 'V5', 'V6']],
(3, 4, True): [['aVL', 'II', 'V1', 'V4'], ['I', 'aVF', 'V2', 'V5'],
['aVR', 'III', 'V3', 'V6']],
}
# ------------------------------------------------------------------
# Image loading & preprocessing
# ------------------------------------------------------------------
def load_image(self, path, target_size=2100):
"""Load, resize, and pad an ECG image.
The image is scaled so that its height equals *target_size* (cubic
interpolation) and then padded with a 20-pixel white border on all
sides. The result is stored in ``self.image``.
Parameters
----------
path : str
Path to the image file.
target_size : int, optional
Target image height in pixels (default ``2100``).
Raises
------
FileNotFoundError
If OpenCV cannot open the file at *path*.
"""
img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
if img is None:
raise FileNotFoundError(f"Cannot read image: {path}")
resample_factor = target_size / img.shape[0]
img = cv2.resize(img,
(int(img.shape[1] * resample_factor),
int(img.shape[0] * resample_factor)),
interpolation=cv2.INTER_CUBIC)
self.image = cv2.copyMakeBorder(img, 20, 20, 20, 20,
cv2.BORDER_CONSTANT, value=[255, 255, 255])
def preprocess_image(self):
"""Apply shadow removal and Gaussian smoothing to ``self.image``.
The result is stored in ``self.processed_image`` and is used as
input for all subsequent YOLO inference calls.
"""
rem = shadow_removal(self.image)
self.processed_image = cv2.GaussianBlur(rem, (3, 3), 0)
# ------------------------------------------------------------------
# Segmentation
# ------------------------------------------------------------------
def segment_leads(self):
"""Run patched YOLO instance segmentation at three crop scales.
The segmentation model is applied to overlapping image patches at
crop factors of 4, 4.5, and 5 (relative to image height).
Detections from each pass are combined with NMS
(``nms_threshold=0.5``) and stored in ``self.lead_segmentation``
as a list of three ``CombineDetections`` objects.
"""
segmentations = []
for shape in [4, 4.5, 5]:
element_crops = MakeCropsDetectThem(
image=cv2.cvtColor(self.processed_image, cv2.COLOR_GRAY2BGR),
model_path=self.segmentation_model,
segment=True,
show_crops=False,
shape_x=int(self.processed_image.shape[0] // shape),
shape_y=int(self.processed_image.shape[0] // shape),
overlap_x=50,
overlap_y=50,
conf=0.8,
iou=0.7,
classes_list=[0],
)
segmentations.append(CombineDetections(element_crops, nms_threshold=0.5))
self.lead_segmentation = segmentations
def make_segmentation_mask(self):
"""Rasterise all segmented polygons into a single binary mask.
Polygons from all three segmentation passes in
``self.lead_segmentation`` are filled and merged into a combined
mask. A morphological opening (5 × 5 kernel) removes small
spurious regions. The result is stored in ``self.mask_image``
(uint8, values 0 or 255).
"""
height, width = self.image.shape[:2]
combined_mask = np.zeros((height, width), dtype=np.uint8)
for segmentation in self.lead_segmentation:
for poly in segmentation.filtered_polygons:
pts = np.array(poly, dtype=np.int32)
if pts.ndim == 2:
pts = [pts]
cv2.fillPoly(combined_mask, pts, color=255)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
self.mask_image = cv2.morphologyEx(combined_mask, cv2.MORPH_OPEN, kernel)
# ------------------------------------------------------------------
# Row detection
# ------------------------------------------------------------------
def find_row_centers(self):
"""Detect the vertical centre of each ECG lead row.
Projects the binary mask onto the vertical axis (row sums) and
applies ``scipy.signal.find_peaks`` twice: once to identify all
peaks, and a second time with an adaptive minimum distance
(⅔ × mean inter-peak spacing) to consolidate merged rows.
Sets
----
self.row_centers : np.ndarray
Y-pixel indices of each row centre.
self.first_peak_start : int
Y-pixel where the topmost row's signal begins.
self.last_peak_end : int
Y-pixel where the bottommost row's signal ends.
"""
image_height, image_width = self.mask_image.shape[:2]
proj = np.sum(self.mask_image, 1)
height = (image_width // 10) * 255
distance = image_height // 30
peaks, _ = find_peaks(proj, height=height, distance=distance)
row_centers, _ = find_peaks(
proj, height=height,
distance=int(np.mean(np.diff(peaks)) * (2 / 3))
)
self.row_centers = row_centers
if len(peaks) > 0:
first_peak = peaks[0]
start_index = first_peak
zero_gap = 0
for i in range(first_peak - 1, -1, -1):
if proj[i] == 0:
zero_gap += 1
if zero_gap > 2:
break
else:
zero_gap = 0
start_index = i
self.first_peak_start = start_index
last_peak = peaks[-1]
end_index = last_peak
zero_gap = 0
for i in range(last_peak + 1, image_height):
if proj[i] == 0:
zero_gap += 1
if zero_gap > 2:
break
else:
zero_gap = 0
end_index = i
self.last_peak_end = end_index
def get_roi(self):
"""Compute the vertical region-of-interest (ROI) spanning all lead rows.
Extends ⅔ of the mean row spacing above the first row centre and
below the last. Stores the result as ``self.roi = (min_y, max_y)``.
"""
spacing = 2 / 3 * np.mean(np.diff(self.row_centers))
min_y = max(0, self.row_centers[0] - spacing)
max_y = min(self.image.shape[0], self.row_centers[-1] + spacing)
self.roi = (min_y, max_y)
# ------------------------------------------------------------------
# YOLO inference helpers — GPU-safe wrappers
# ------------------------------------------------------------------
def _predict_safe(self, model, image_bgr, **kwargs):
"""Run a YOLO model prediction in a thread-safe manner.
On CUDA: wraps the call in a dedicated ``torch.cuda.Stream`` and
synchronises before returning, preventing contention on the
default stream when multiple threads call this simultaneously.
On CPU: wraps with ``torch.no_grad()`` only.
Parameters
----------
model : ultralytics.YOLO
The detection/classification model to run.
image_bgr : np.ndarray
BGR image array as expected by Ultralytics.
**kwargs
Forwarded to ``model.predict()`` (e.g. ``conf``, ``iou``).
Returns
-------
list
Ultralytics ``Results`` objects.
"""
if torch.cuda.is_available():
stream = torch.cuda.Stream()
with torch.no_grad():
with torch.cuda.stream(stream):
results = model.predict(image_bgr, verbose=False, **kwargs)
stream.synchronize()
else:
with torch.no_grad():
results = model.predict(image_bgr, verbose=False, **kwargs)
return results
# ------------------------------------------------------------------
# Timing helper
# ------------------------------------------------------------------
@staticmethod
def _timed(label, fn, *args, **kwargs):
"""Call *fn* with *args*/*kwargs*, print its wall-clock duration, and return its result.
Parameters
----------
label : str
Human-readable stage name printed alongside the elapsed time.
fn : callable
The stage function to time.
*args, **kwargs
Forwarded to *fn*.
Returns
-------
Any
Whatever *fn* returns.
"""
t = time.time()
result = fn(*args, **kwargs)
print(f" ⏱ {label}: {time.time() - t:.1f}s", flush=True)
return result
# ------------------------------------------------------------------
# Box & name extraction
# ------------------------------------------------------------------
def extract_lead_boxes(self):
"""Detect lead bounding boxes with ``box_model`` and filter to the ROI.
Runs ``_predict_safe`` on the preprocessed BGR image at confidence
0.8, then discards boxes whose ``y1``/``y2`` coordinates fall
outside ``self.roi``. Sets ``self.lead_bboxes`` as a list of
``[x1, y1, x2, y2]`` float lists.
"""
image_bgr = cv2.cvtColor(self.processed_image, cv2.COLOR_GRAY2BGR)
results = self._predict_safe(self.box_model, image_bgr, conf=0.8)
min_y, max_y = self.roi
lead_boxes = []
for r in results:
for box in r.boxes:
x1, y1, x2, y2 = box.xyxy.cpu().numpy()[0].tolist()
if y1 >= min_y and y2 <= max_y:
lead_boxes.append([x1, y1, x2, y2])
self.lead_bboxes = lead_boxes
def extract_lead_name_boxes(self):
"""Detect and classify lead name labels with ``lead_name_model``.
Runs at confidence 0.8, filters to the ROI, and stores results in
``self.lead_name_bboxes`` as a list of
``{'bbox': [x1, y1, x2, y2], 'class_name': str}`` dicts.
"""
image_bgr = cv2.cvtColor(self.processed_image, cv2.COLOR_GRAY2BGR)
results = self._predict_safe(self.lead_name_model, image_bgr, conf=0.8)
min_y, max_y = self.roi
name_boxes = []
for r in results:
for box in r.boxes:
x1, y1, x2, y2 = box.xyxy.cpu().numpy()[0].tolist()
if y1 >= min_y and y2 <= max_y:
cls_id = int(box.cls.cpu().numpy()[0])
cls_name = self.lead_name_model.names[cls_id]
name_boxes.append({'bbox': [x1, y1, x2, y2], 'class_name': cls_name})
self.lead_name_bboxes = name_boxes
def extract_reference_pulses(self):
"""Detect calibration pulse boxes with ``pulse_model``.
Runs at confidence 0.7 (lower than lead detection to improve
recall on small pulses). For each detection, stores the
corresponding image crop alongside the bounding-box coordinates.
Sets ``self.reference_pulses`` as a list of
``{'bbox': [x1, y1, x2, y2], 'image': np.ndarray}`` dicts.
"""
image_bgr = cv2.cvtColor(self.processed_image, cv2.COLOR_GRAY2BGR)
results = self._predict_safe(self.pulse_model, image_bgr, conf=0.7)
pulse_boxes = []
for r in results:
for box in r.boxes:
coord = box.xyxy.cpu().numpy()[0].tolist()
pulse_boxes.append({
'image': self.image[int(coord[1]) - 5:int(coord[3]) + 5,
int(coord[0]) - 5:int(coord[2]) + 5],
'bbox': coord,
})
self.reference_pulses = pulse_boxes
# ------------------------------------------------------------------
# Visualisation helpers
# ------------------------------------------------------------------
def visualize_boxes(self, task='Lead name', show_axis=False):
"""Overlay detection bounding boxes on the original image.
Parameters
----------
task : {'Lead name', 'Lead box', 'Reference pulse'}
Which set of boxes to draw.
show_axis : bool, optional
Whether to display axis ticks (default ``False``).
"""
img_copy = cv2.cvtColor(self.image.copy(), cv2.COLOR_GRAY2BGR)
if task == 'Lead name':
if not self.lead_name_bboxes:
print("Lead name boxes not extracted.")
return
for box in self.lead_name_bboxes:
x1, y1, x2, y2 = map(int, box['bbox'])
cv2.rectangle(img_copy, (x1, y1), (x2, y2), (255, 0, 0), 2)
cv2.putText(img_copy, box['class_name'], (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 3)
elif task == 'Lead box':
if not self.lead_bboxes:
print("Lead boxes not extracted.")
return
for bbox in self.lead_bboxes:
x1, y1, x2, y2 = map(int, bbox)
cv2.rectangle(img_copy, (x1, y1), (x2, y2), (255, 0, 0), 2)
elif task == 'Reference pulse':
if not self.reference_pulses:
print("Reference pulses not extracted.")
return
for bbox in self.reference_pulses:
x1, y1, x2, y2 = map(int, bbox['bbox'])
cv2.rectangle(img_copy, (x1, y1), (x2, y2), (255, 0, 0), 2)
else:
print(f"Unknown task: {task}")
return
plt.figure(figsize=(12, 10))
plt.imshow(cv2.cvtColor(img_copy, cv2.COLOR_BGR2RGB))
if not show_axis:
plt.axis('off')
plt.show()
def visualize_segmentation(self, show_boxes=False, show_axis=False,
fill_mask=True, thickness=1):
"""Render all segmented lead polygons on the original image.
Aggregates results from all three segmentation passes in
``self.lead_segmentation`` and passes them to
``patched_yolo_infer.visualize_results``.
Parameters
----------
show_boxes : bool, optional
Also draw bounding boxes around each polygon (default ``False``).
show_axis : bool, optional
Display axis ticks (default ``False``).
fill_mask : bool, optional
Fill polygon interiors with a translucent colour (default ``True``).
thickness : int, optional
Polygon outline thickness in pixels (default ``1``).
"""
all_confidences, all_boxes, all_polygons = [], [], []
all_classes_ids, all_classes_names = [], []
for seg in self.lead_segmentation:
all_confidences.extend(seg.filtered_confidences)
all_boxes.extend(seg.filtered_boxes)
all_polygons.extend(seg.filtered_polygons)
all_classes_ids.extend(seg.filtered_classes_id)
all_classes_names.extend(seg.filtered_classes_names)
visualize_results(
img=cv2.cvtColor(self.image, cv2.COLOR_GRAY2RGB),
confidences=all_confidences,
boxes=all_boxes,
polygons=all_polygons,
classes_ids=all_classes_ids,
classes_names=all_classes_names,
segment=True,
thickness=thickness,
fill_mask=fill_mask,
show_boxes=show_boxes,
show_class=False,
axis_off=(not show_axis),
)
# ------------------------------------------------------------------
# Calibration (volt/pixel & time/pixel)
# ------------------------------------------------------------------
def get_reference_scale(self):
"""Derive pixel-to-physical calibration constants from the calibration pulses.
For each pulse in ``self.reference_pulses``, the method:
1. Enhances contrast with CLAHE and binarises with multi-Otsu thresholding.
2. Detects horizontal and vertical lines via morphological filtering and
Hough transform to measure the pulse amplitude (voltage) and width (time).
3. Refines the time calibration using the Line Segment Detector (LSD).
Sets
----
self.volt_per_pixel : float
Millivolts per pixel (vertical axis). Calibrated to the standard
1 mV / 10 mm calibration pulse.
self.time_per_pixel : float
Seconds per pixel (horizontal axis). Calibrated to 0.2 s between
the two inner vertical edges of the calibration pulse.
Raises
------
RuntimeError
If no valid pulse yields voltage or time measurements.
"""
voltages, times, dist = [], [], []
def _line_length(x1, y1, x2, y2):
return np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
for pulse_idx, pulse in enumerate(self.reference_pulses):
try:
img = pulse['image']
if img is None or img.size == 0:
continue
h, w = img.shape
if h < 10 or w < 10:
continue
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
enhanced = clahe.apply(img)
blurred = cv2.GaussianBlur(enhanced, (3, 3), 0)
thresholds = threshold_multiotsu(blurred, classes=2)
regions = np.digitize(blurred, bins=thresholds)
binary = (regions == 0).astype(np.uint8) * 255
h_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (25, 1))
v_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 25))
h_lines_img = cv2.morphologyEx(binary, cv2.MORPH_OPEN, h_kernel)
v_lines_img = cv2.morphologyEx(binary, cv2.MORPH_OPEN, v_kernel)
h_lines_raw = cv2.HoughLinesP(
h_lines_img, rho=1, theta=np.pi / 180,
threshold=w // 4, minLineLength=w // 2, maxLineGap=1
)
v_lines_raw = cv2.HoughLinesP(
v_lines_img, rho=1, theta=np.pi / 180,
threshold=h // 4, minLineLength=h // 2, maxLineGap=1
)
combined_lines = []
if h_lines_raw is not None:
combined_lines.extend(h_lines_raw)
if v_lines_raw is not None:
combined_lines.extend(v_lines_raw)
horizontal_lines, vertical_lines = [], []
for line in combined_lines:
x1, y1, x2, y2 = line[0]
angle = np.arctan2(abs(y2 - y1), abs(x2 - x1)) * 180 / np.pi
if angle < 10 or angle > 170:
horizontal_lines.append((x1, y1, x2, y2))
elif 80 < angle < 100:
vertical_lines.append((x1, y1, x2, y2))
if len(vertical_lines) >= 2:
longest_v = sorted(vertical_lines,
key=lambda l: _line_length(*l), reverse=True)[:2]
xc1 = (longest_v[0][0] + longest_v[0][2]) / 2
xc2 = (longest_v[1][0] + longest_v[1][2]) / 2
vertical_spacing = abs(xc1 - xc2)
volt_vals = sorted([_line_length(*l) for l in vertical_lines],
reverse=True)[:2]
if volt_vals:
voltages.append(volt_vals)
if vertical_spacing > 5:
times.append(vertical_spacing)
# LSD for more precise time calibration
lsd = cv2.createLineSegmentDetector(refine=2)
lsd_lines, _, _, _ = lsd.detect(v_lines_img)
min_length = h / 3
angle_tol_rad = np.deg2rad(5)
filtered = []
if lsd_lines is not None:
for line in lsd_lines:
x1, y1, x2, y2 = line[0]
length = np.hypot(x2 - x1, y2 - y1)
if length >= min_length:
angle = np.arctan2(y2 - y1, x2 - x1)
if np.abs(np.abs(angle) - np.pi / 2) <= angle_tol_rad:
filtered.append([[x1, y1, x2, y2]])
if len(filtered) >= 4:
filtered.sort(
key=lambda l: np.hypot(l[0][2] - l[0][0], l[0][3] - l[0][1]),
reverse=True
)
top4 = filtered[:4]
top4.sort(key=lambda l: (l[0][0] + l[0][2]) / 2)
midpoints = []
for l1, l2 in [(top4[0], top4[1]), (top4[2], top4[3])]:
xc1 = (l1[0][0] + l1[0][2]) / 2
xc2 = (l2[0][0] + l2[0][2]) / 2
midpoints.append((xc1 + xc2) / 2)
dist.append(midpoints[1] - midpoints[0])
except Exception as e:
print(f" ⚠ Skipping pulse {pulse_idx}: {e}", flush=True)
continue
if not voltages:
raise RuntimeError("No valid reference pulses found for voltage calibration.")
if not dist:
raise RuntimeError("No valid reference pulses found for time calibration.")
self.volt_per_pixel = 1 / np.mean(voltages)
self.time_per_pixel = 0.2 / np.mean(dist)
# ------------------------------------------------------------------
# Layout helpers
# ------------------------------------------------------------------
def make_bounding_box_features(self, box, axis):
"""Extract three positional features from a bounding box along one axis.
Parameters
----------
box : list[float]
Bounding box as ``[x1, y1, x2, y2]``.
axis : {'x', 'y'}
Axis along which to compute features.
Returns
-------
list[float]
``[axis_min, axis_center, axis_max]``.
"""
if axis == 'y':
axis_min, axis_max = box[1], box[3]
else:
axis_min, axis_max = box[0], box[2]
axis_center = (axis_min + axis_max) / 2
return [axis_min, axis_center, axis_max]
def bounding_boxes_kmeans(self, bounding_boxes, axis='y',
k_min=1, k_max=13, return_model=True):
"""Cluster bounding boxes along one axis using K-Means.
Tries all values of *k* in ``[k_min, k_max]`` and selects the one
that maximises the silhouette score. Cluster labels are sorted by
mean position along *axis* (ascending).
Parameters
----------
bounding_boxes : list[list[float]]
List of ``[x1, y1, x2, y2]`` boxes.
axis : {'x', 'y'}, optional
Axis along which to cluster (default ``'y'``).
k_min : int, optional
Minimum number of clusters (default ``1``).
k_max : int, optional
Maximum number of clusters (default ``13``).
return_model : bool, optional
If ``True``, also return the fitted ``KMeans`` model and the
label remapping dict (default ``True``).
Returns
-------
sorted_labels : np.ndarray of int
Cluster index (sorted) for each input box.
best_k : int
Optimal number of clusters.
sorted_centers : np.ndarray
Mean positional value of each cluster, sorted ascending.
label_map : dict
Mapping from original K-Means label → sorted label.
best_model : sklearn.cluster.KMeans
Fitted model (only when ``return_model=True``).
Raises
------
ValueError
If *axis* is not ``'x'`` or ``'y'``, or if there are fewer
boxes than *k_min*.
"""
if axis not in ('x', 'y'):
raise ValueError("Axis must be 'x' or 'y'")
if len(bounding_boxes) < k_min:
raise ValueError("Not enough bounding boxes to cluster")
features = np.array([self.make_bounding_box_features(b, axis)
for b in bounding_boxes])
best_score, best_k = -1, k_min
best_labels = best_centers = best_model = None
for k in range(k_min, min(k_max + 1, len(bounding_boxes))):
kmeans = KMeans(n_clusters=k, random_state=42, n_init="auto")
labels = kmeans.fit_predict(features)
score = silhouette_score(features, labels)
if score > best_score:
best_score = score
best_k = k
best_labels = labels
best_centers = kmeans.cluster_centers_
best_model = kmeans
cluster_avgs = best_centers.mean(axis=1)
sorted_indices = np.argsort(cluster_avgs)
label_map = {old: new for new, old in enumerate(sorted_indices)}
sorted_labels = np.array([label_map[l] for l in best_labels])
sorted_centers = cluster_avgs[sorted_indices]
if return_model:
return sorted_labels, best_k, sorted_centers, label_map, best_model
return sorted_labels, best_k, sorted_centers, label_map
def check_cabrera(self, num_rows, num_cols):
"""Determine whether the ECG uses Cabrera lead ordering.
The heuristic varies by layout:
* **12- or 6-row layouts:** compares the vertical spacing of
augmented-limb leads (aVR/aVL/aVF) against precordial leads.
Cabrera re-orders the limb leads so their spacing differs.
* **4-row, 3-col / 5-row layouts:** checks the vertical spread
of augmented leads (high std → interleaved → Cabrera).
* **3-row / 4-col layouts:** checks the horizontal spread of
augmented leads.
Sets ``self.is_cabrera`` as a side-effect.
Parameters
----------
num_rows : int
Number of detected lead rows.
num_cols : int
Number of detected lead columns.
Returns
-------
bool
``True`` if Cabrera ordering is detected.
"""
if num_rows in [13, 12, 7, 6]:
av_leads = [b for b in self.lead_name_bboxes
if b['class_name'] in {'aVR', 'aVL', 'aVF'}]
v_leads = [b for b in self.lead_name_bboxes
if b['class_name'] in {'V1', 'V2', 'V3', 'V4', 'V5', 'V6'}]
if not av_leads or not v_leads:
return False
y_v = sorted([(b['bbox'][1] + b['bbox'][3]) / 2 for b in v_leads])
y_av = sorted([(b['bbox'][1] + b['bbox'][3]) / 2 for b in av_leads])
threshold = 30
diff_v = np.diff(y_v)
diff_av = np.diff(y_av)
diff_v = diff_v[np.abs(diff_v) > threshold]
diff_av = diff_av[np.abs(diff_av) > threshold]
if len(diff_v) == 0 or len(diff_av) == 0:
return False
if abs(np.min(diff_v) - np.min(diff_av)) > (0.25 * np.min(diff_v)):
self.is_cabrera = True
return True
self.is_cabrera = False
return False
elif (num_rows == 4 and num_cols == 3) or num_rows == 5:
av_leads = [b for b in self.lead_name_bboxes
if b['class_name'] in {'aVR', 'aVL', 'aVF'}]
if not av_leads:
return False
y_coords = [(b['bbox'][1] + b['bbox'][3]) / 2 for b in av_leads]
self.is_cabrera = np.std(y_coords) > 25
return self.is_cabrera
elif (num_rows == 4 and num_cols == 4) or num_rows == 3:
av_leads = [b for b in self.lead_name_bboxes
if b['class_name'] in {'aVR', 'aVL', 'aVF'}]
if not av_leads:
return False
x_coords = [(b['bbox'][0] + b['bbox'][2]) / 2 for b in av_leads]
self.is_cabrera = np.std(x_coords) > 25
return self.is_cabrera
def get_layout(self, num_rows):
"""Map the detected row count to a standard ECG layout.
Calls :meth:`check_cabrera` to determine lead ordering, sets
``self.layout`` (2-D list of lead name strings) and
``self.has_calibration_pulse``, and returns the number of columns.
Supported row counts
--------------------
* 13 → 12×1 with calibration pulse
* 12 → 12×1 without calibration pulse
* 7 → 6×2 with calibration pulse
* 6 → 6×2 without calibration pulse
* 5 → 4×3 with calibration pulse
* 4 → 3×4 or 4×3 (disambiguated by V-lead spatial distribution)
* 3 → 3×4 without calibration pulse
Parameters
----------
num_rows : int
Number of detected lead rows.
Returns
-------
int
Number of lead columns in the detected layout.
"""
if num_rows == 13:
num_cols = 1
self.has_calibration_pulse = True
cabrera = self.check_cabrera(num_rows, num_cols)
self.layout = self.standard_layouts[(12, 1, cabrera)]
elif num_rows == 12:
num_cols = 1
self.has_calibration_pulse = False