Repository files navigation

⚡ ECGLight: Compute-Light Framework for Paper ECG Digitization & Myocardial Infarction Screening

arXivPython 3.9+PyTorchUltralytics YOLOv11Streamlit WorkstationLicense: Non-Commercial


📌 Abstract & Key Highlights

ECGLight is an end-to-end, compute-light framework and interactive web workstation for converting paper/photographed 12-lead ECG records into high-fidelity 500 Hz digitized signals and performing automated screening for Myocardial Infarction (MI) and Occlusive MI (OMI) pathologies.

💡 Designed for Low-Resource & Remote Settings: ECGLight runs completely on CPU-only hardware in <30 seconds per ECG without requiring cloud connectivity or expensive GPU infrastructure, democratizing AI-based decision support for clinics worldwide.

✨ Key Features & Capabilities

  • 📷 High-Fidelity Signal Digitization: Multi-stage computer vision pipeline combining sequential YOLOv11 object detection, scale calibration via Hough lines, K-Means grid construction, and an anti-leakage connected-component filter to extract clean 500 Hz 12-lead signals from smartphone photos or scans.
  • ❤️ High-Accuracy MI & OMI Screening:
    • 95.51% Accuracy ($F_1 = 0.9519$) for MI detection on the benchmark PTB-XL dataset (21,799 ECGs).
    • 88.89% Accuracy ($F_1 = 0.8862$) for Occlusive MI (OMI) screening on the hospital-acquired ECG-Matrix dataset.
  • ⚡ On-Device & Resource-Efficient: Fully functional on standard consumer laptop CPUs or CUDA GPUs.
  • 🖥️ Interactive Web Dashboard Workstation: Streamlit workstation featuring real-time signal viewing, step-by-step digitization previews, R-peak beat segmentation, and downloadable diagnostic prediction tables.

📰 News & Updates


📌 Table of Contents


🖥️ Web Dashboard Workstation Overview

The ECGLight workstation provides a responsive user interface designed for clinical workflow exploration, research, and education. It unifies the computer vision digitization and diagnostic classification models into a seamless local web application.

Workstation Modules

  1. 📷 ECG Image Digitizer:

    • Upload scanned or photographed ECG images (.png, .jpg, .jpeg).
    • Execute the sequential YOLOv11 detection pipeline with real-time visual progress indicators.
    • Summarizes detected leads, calibrated sampling rates, and total extracted samples.
    • Automatically exports the digitized time-series CSV to output/digitization/latest_digitized.csv.
  2. 📈 ECG Signal Viewer:

    • Interactive multi-channel ECG signal visualization using native Streamlit/Vega-Lite charts with zoom, pan, and hover tooltips.
    • Supports stacked subplots (with distinct clinical lead colorings) and multi-lead overlay modes.
    • Computes statistical summaries (mean, SD, min/max, voltage range) and row-level previewing.
  3. ❤️ ECG Classification Engine:

    • Evaluates cardiac pathologies using pre-trained time-series ensemble and deep learning classifiers.
    • Automatically segments raw signals into heartbeats around R-peaks using the Pan-Tompkins algorithm.
    • Inference Mode (Unlabeled Data): Generates downloadable Predictions Tables with predicted class labels and probability confidence scores.
    • Evaluation Mode (Ground-Truth Labeled Data): Displays interactive evaluation metrics (Accuracy, $F_1$-Score, Sensitivity, Specificity, Confusion Matrix).

🔄 End-to-End Workflow

The pipeline operates in four coordinated phases: Digitization $ ightarrow$ Analysis $ ightarrow$ Segmentation $ ightarrow$ Classification. Architectural flowcharts for each phase are provided in the How It Works sections below.


🚀 Installation & Setup

Prerequisites

  • Python: 3.9+ (tested on Python 3.9 and 3.11)
  • Hardware: Standard CPU (CUDA-capable GPU optional, automatically detected)

Step-by-Step Installation

  1. Clone the Repository:

    git clone https://github.com/scai-lab/ECG-Digitization-Classification.git
    cd ECG-Digitization-Classification
  2. Create and Activate Conda Environment:

    conda env create -f environment.yml
    conda activate infer

    [!IMPORTANT] Windows Compatibility & TensorFlow Setup: If running on Windows and encountering DLL loading errors (ImportError: DLL load failed while importing _pywrap_tensorflow_internal), install the pinned TensorFlow and Protobuf pairing:

    pip install tensorflow==2.15.0 protobuf==4.25.3
  3. Download Pre-Trained Model Weights: The YOLOv11 detection checkpoints and pre-trained time-series classifiers are hosted on Polybox due to file size constraints:

    👉 Download Pre-Trained Models Directory (ETH Zürich Polybox)

    Extract the downloaded archive and place the models/ directory directly into the root of the project workspace:

    models/
    ├── digitization_models/
    │ ├── yolo11_full/weights/best.pt
    │ ├── yolo11_lead/weights/best.pt
    │ ├── yolo11_pulse/weights/best.pt
    │ └── yolo11_patch/weights/best.pt
    └── classifier_models/
    ├── mi_vs_normal_segmented/
    ├── omi_vs_nonomi/
    └── ecg_surgery/
    
  4. Launch the Web Dashboard Workstation:

    streamlit run app.py

🧠 Pre-Trained Classifiers & Tasks

The classification engine supports three distinct diagnostic tasks using the pre-trained weights in models/classifier_models/:

Diagnostic TaskModel ArchitectureExpected Input Tensor ShapeTest AccuracyTarget Positive Class
Normal vs Myocardial Infarction (MI)Arsenal Ensemble12 leads $ imes$ 140 timesteps92.3%MYOCARDIAL_INFARCTION
Occlusive MI (OMI) vs Non-OMIRocket Classifier12 leads $ imes$ 141 timesteps88.9%OMI
Pre-Procedural vs Post-Procedural MIInceptionTime Deep Net12 leads $ imes$ 140 timesteps91.4%pre-procedural MI
  • Arsenal: An ensemble of ROCKET classifiers utilizing random convolutional kernels combined with ridge regression feature classification.
  • Rocket: Random Omni-directional Kernel Extraction classifier computing high-dimensional time-series representations.
  • InceptionTime: A deep 1D convolutional neural network ensemble leveraging multi-scale temporal kernel convolutions.

🚀 Command Line Usage

Batch Signal Digitization (run_org.py)

Process structured directories of paper ECG scans in batch mode:

  1. Configure dataset directory paths in run_org.py:

    ORGANIZED_DIR="../ecg_files/ECG_organized_all"# Input dataset rootOUTPUT_DIR="../ecg_files/ECG_digitized"# Destination for CSVsCATEGORIES= ["pre", "index", "post"] # Sub-directories
  2. Run the batch digitization script:

    python run_org.py

Command-Line Model Inference (run_inference.py)

Run standalone inference on pre-digitized CSV datasets:

# 1. Normal vs MI Classification (Arsenal Model)
python archive/classification/run_inference.py --model mi_vs_normal_segmented --input data/ptb_xl/segmented_heartbeats.csv
# 2. Occlusive MI (OMI) vs Non-OMI Classification (Rocket Model)
python archive/classification/run_inference.py --model omi_vs_nonomi --input data/ecg_matrix_omi_segmented_50_150_90.csv
# 3. Custom Output Destination
python archive/classification/run_inference.py --model ecg_surgery --input data/ecg_surgery_segmented_50_150_70.csv --output results/surgery_preds.csv

📁 Repository Structure & Directory Organization

.
├── app.py # Streamlit application main router
├── config.py # Centralized configuration and model registry
├── digitization.py # Core ECGImage extraction pipeline class
├── environment.yml # Conda environment dependency specification
├── LICENSE # Non-commercial academic license agreement
├── README.md # Repository documentation
│
├── backend/ # Dashboard background execution adapters
│ ├── __init__.py # Package initializer
│ ├── digitization_runner.py # YOLO loader and single-image processor
│ └── classification_runner.py # Model loader and inference adapter
│
├── utils/ # Streamlit front-end UI view components
│ ├── __init__.py # Package initializer
│ ├── branding.py # Header titles and institutional footer logos
│ ├── css.py # Custom clinical theme and styling utilities
│ ├── hardware.py # Hardware detector (CPU/GPU)
│ ├── page_digitizer.py # ECG Digitizer page view
│ ├── page_csv_viewer.py # Interactive Signal Viewer page view
│ └── page_classifier.py # Classification workstation page view
│
├── models/ # Relocated YOLO checkpoints and classifiers (external)
│ ├── digitization_models/ # YOLOv11 weights (full, lead, pulse, patch)
│ └── classifier_models/ # Pre-trained classifier weights (Arsenal, Rocket, InceptionTime)
│
└── archive/ # Archived research, training, and CLI scripts (local)
└── classification/ # Baseline training and evaluation scripts

📷 How It Works: Signal Digitization

The core engine in digitization.py executes a multi-stage computer vision workflow to convert image pixels into calibrated voltage waveforms:

graph TD
A[ECG Image Upload] --> B[Preprocessing: Otsu & Blurring]
B --> C[YOLOv11 Detection & Segmentation]
subgraph YOLOv11 Models
C1[yolo11_full: Lead Boundaries]
C2[yolo11_lead: Text Name Labels]
C3[yolo11_pulse: Calibration Pulses]
C4[yolo11_patch: Waveform Segments]
end
C --> C1 & C2 & C3 & C4
C1 & C2 & C3 & C4 --> D[Hough Lines Calibration]
D --> E[K-Means Row & Column Grid Construction]
E --> F[Anti-Leakage Connected Components Filter]
F --> G[Centroid Trace & Resampling to 500Hz]
G --> H[Export latest_digitized.csv]
Loading
  1. Image Preprocessing: Cleans input scans using shadow removal, Otsu binarization, and Gaussian blurring to separate ink traces from paper texture.
  2. YOLO Segmentation: Applies patched YOLO segmentation models across multiple crop scales (, 4.5×, ) to bound individual lead regions.
  3. Multi-Model Object Detection: Runs YOLO detectors in parallel:
    • yolo11_full: Bounding boxes for the 12 lead channels.
    • yolo11_lead: Text label identification (I, II, aVR, V1-V6).
    • yolo11_pulse: Bounding boxes for 1 mV calibration reference pulses.
  4. Scale Calibration: Fits Hough lines to calibration pulse boundaries to compute exact voltage scaling ($ ext{V}/ ext{px}$) and time scaling ($ ext{s}/ ext{px}$).
  5. Grid Construction: Employs K-Means clustering on lead coordinates to construct regular grid layouts (3×4, 4×3, 6×2, 12×1) and resolve standard Cabrera lead ordering.
  6. Contour Tracing & Anti-Leakage Filtering: Traces pixel centroids, baseline-corrects waveforms, and applies an anti-leakage connected-component filter per crop to isolate primary waveform traces from adjacent lead leakage. Signals are resampled to 500 Hz calibrated in mV.

📈 How It Works: Signal Analysis & Visualization

graph TD
A[Upload Digitized CSV] --> B[Parse Lead Voltages & Timestamps]
B --> C[Vega-Lite Interactive Visualizer]
C --> C1[Render Stacked Leads]
C --> C2[Render Overlaid Signals]
B --> D[Compute Signal Statistics: Mean, SD, Min/Max]
D --> E[Display Summary Dataframes & Row Previews]
Loading
  1. Signal Parsing: Validates multi-lead CSV headers, timestamps, and sampling consistency.
  2. Interactive Rendering: Native Vega-Lite charts enable client-side pan, zoom, and multi-channel hover tooltips.
  3. Statistical Profiling: Calculates lead-level statistical metrics (mean, standard deviation, voltage range, min/max).

⚡ How It Works: Heartbeat Segmentation

Prepares continuous 12-lead signals for classification models via Pan-Tompkins R-peak detection:

graph TD
A[Digitized 500Hz Signal] --> B[Bandpass Filter 5-15Hz]
B --> C[Derivative Filter]
C --> D[Squaring Operation]
D --> E[Moving Window Integration]
E --> F[Adaptive Thresholding & R-Peak Search]
F --> G[Extract 140-sample Beats: 50ms pre-R, 150ms post-R]
G --> H[Max-Absolute Voltage Normalization]
Loading
  1. Bandpass Filtering: 5–15 Hz bandpass filter isolates QRS energy while suppressing muscle artifact and baseline wander.
  2. Differentiation & Squaring: Highlights steep QRS slopes and attenuates P/T waves.
  3. Moving Window Integration: Integrates energy across a 150 ms window to delineate QRS complexes.
  4. Adaptive Thresholding: Dynamically searches for R-peak maxima.
  5. Beat Windowing & Normalization: Extracts beat windows centered around R-peaks (50 ms pre-R, 150 ms post-R), normalizes max-absolute voltage, and formats output tensors (140/141 timesteps).

🧠 How It Works: Cardiac Classification

graph TD
A[Segmented Heartbeats] --> B[Numpy3D Reshaping: N_instances × 12_leads × N_timesteps]
B --> C[Select Classification Task]
subgraph Model Registry
C1[Normal vs MI: Arsenal]
C2[OMI vs non-OMI: Rocket]
C3[Pre vs Post-Procedural MI: InceptionTime]
end
C --> C1 & C2 & C3
C1 & C2 & C3 --> D[Load Pre-Trained Pickled Estimator]
D --> E[Predict Class Labels & Probabilities]
E --> F[Generate Downloadable Predictions CSV]
Loading
  1. Tensor Formatting: Formats heartbeat segments into 3D NumPy arrays (N_samples, 12_leads, N_timesteps).
  2. Model Evaluation: Invokes the pre-trained pickled estimator for the selected diagnostic endpoint.
  3. Report Generation: Formats class predictions, confidence probabilities, and diagnostic metrics for export.

🤝 Collaborating Institutions

This research project was developed in multi-center academic and clinical collaboration:

ETH ZürichIstituto Cardiocentro Ticino (EOC)USIUniversità della Campania Luigi Vanvitelli


👥 Authors & Contact

  • Shreyasvi Natrajsnatraj@ethz.ch
  • Cyrus Achtari
  • Felice Gragnano
  • Andrea Milzi
  • Marco Valgimigli
  • Diego Paez-Granados

📄 Citation

If you use ECGLight or its pre-trained models in your research, please cite our arXiv preprint:

@article{natraj2026ecglight,
title={ECGLight: Compute-Light Framework For Paper ECG Digitization and Myocardial Infarction Screening},
author={Natraj, Shreyasvi and Achtari, Cyrus and Gragnano, Felice and Milzi, Andrea and Valgimigli, Marco and Paez-Granados, Diego},
journal={arXiv preprint arXiv:2607.07683},
year={2026},
url={https://arxiv.org/abs/2607.07683},
doi={10.48550/arXiv.2607.07683}
}

APA Citation: Natraj, S., Achtari, C., Gragnano, F., Milzi, A., Valgimigli, M., & Paez-Granados, D. (2026). ECGLight: Compute-Light Framework For Paper ECG Digitization and Myocardial Infarction Screening. arXiv preprint arXiv:2607.07683. https://arxiv.org/abs/2607.07683


📄 License

This repository and model weights are released under the Non-Commercial Academic and Research License Agreement. Please refer to the LICENSE file for full terms. Free for non-profit academic and research use. Commercial use is strictly prohibited.

About

Directory containing the backend and front end of Paper ECG Digitization and Classification

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

⚡ ECGLight: Compute-Light Framework for Paper ECG Digitization & Myocardial Infarction Screening

arXivPython 3.9+PyTorchUltralytics YOLOv11Streamlit WorkstationLicense: Non-Commercial


📌 Abstract & Key Highlights

ECGLight is an end-to-end, compute-light framework and interactive web workstation for converting paper/photographed 12-lead ECG records into high-fidelity 500 Hz digitized signals and performing automated screening for Myocardial Infarction (MI) and Occlusive MI (OMI) pathologies.

💡 Designed for Low-Resource & Remote Settings: ECGLight runs completely on CPU-only hardware in <30 seconds per ECG without requiring cloud connectivity or expensive GPU infrastructure, democratizing AI-based decision support for clinics worldwide.

✨ Key Features & Capabilities

  • 📷 High-Fidelity Signal Digitization: Multi-stage computer vision pipeline combining sequential YOLOv11 object detection, scale calibration via Hough lines, K-Means grid construction, and an anti-leakage connected-component filter to extract clean 500 Hz 12-lead signals from smartphone photos or scans.
  • ❤️ High-Accuracy MI & OMI Screening:
    • 95.51% Accuracy ($F_1 = 0.9519$) for MI detection on the benchmark PTB-XL dataset (21,799 ECGs).
    • 88.89% Accuracy ($F_1 = 0.8862$) for Occlusive MI (OMI) screening on the hospital-acquired ECG-Matrix dataset.
  • ⚡ On-Device & Resource-Efficient: Fully functional on standard consumer laptop CPUs or CUDA GPUs.
  • 🖥️ Interactive Web Dashboard Workstation: Streamlit workstation featuring real-time signal viewing, step-by-step digitization previews, R-peak beat segmentation, and downloadable diagnostic prediction tables.

📰 News & Updates


📌 Table of Contents


🖥️ Web Dashboard Workstation Overview

The ECGLight workstation provides a responsive user interface designed for clinical workflow exploration, research, and education. It unifies the computer vision digitization and diagnostic classification models into a seamless local web application.

Workstation Modules

  1. 📷 ECG Image Digitizer:

    • Upload scanned or photographed ECG images (.png, .jpg, .jpeg).
    • Execute the sequential YOLOv11 detection pipeline with real-time visual progress indicators.
    • Summarizes detected leads, calibrated sampling rates, and total extracted samples.
    • Automatically exports the digitized time-series CSV to output/digitization/latest_digitized.csv.
  2. 📈 ECG Signal Viewer:

    • Interactive multi-channel ECG signal visualization using native Streamlit/Vega-Lite charts with zoom, pan, and hover tooltips.
    • Supports stacked subplots (with distinct clinical lead colorings) and multi-lead overlay modes.
    • Computes statistical summaries (mean, SD, min/max, voltage range) and row-level previewing.
  3. ❤️ ECG Classification Engine:

    • Evaluates cardiac pathologies using pre-trained time-series ensemble and deep learning classifiers.
    • Automatically segments raw signals into heartbeats around R-peaks using the Pan-Tompkins algorithm.
    • Inference Mode (Unlabeled Data): Generates downloadable Predictions Tables with predicted class labels and probability confidence scores.
    • Evaluation Mode (Ground-Truth Labeled Data): Displays interactive evaluation metrics (Accuracy, $F_1$-Score, Sensitivity, Specificity, Confusion Matrix).

🔄 End-to-End Workflow

The pipeline operates in four coordinated phases: Digitization $ ightarrow$ Analysis $ ightarrow$ Segmentation $ ightarrow$ Classification. Architectural flowcharts for each phase are provided in the How It Works sections below.


🚀 Installation & Setup

Prerequisites

  • Python: 3.9+ (tested on Python 3.9 and 3.11)
  • Hardware: Standard CPU (CUDA-capable GPU optional, automatically detected)

Step-by-Step Installation

  1. Clone the Repository:

    git clone https://github.com/scai-lab/ECG-Digitization-Classification.git
    cd ECG-Digitization-Classification
  2. Create and Activate Conda Environment:

    conda env create -f environment.yml
    conda activate infer

    [!IMPORTANT] Windows Compatibility & TensorFlow Setup: If running on Windows and encountering DLL loading errors (ImportError: DLL load failed while importing _pywrap_tensorflow_internal), install the pinned TensorFlow and Protobuf pairing:

    pip install tensorflow==2.15.0 protobuf==4.25.3
  3. Download Pre-Trained Model Weights: The YOLOv11 detection checkpoints and pre-trained time-series classifiers are hosted on Polybox due to file size constraints:

    👉 Download Pre-Trained Models Directory (ETH Zürich Polybox)

    Extract the downloaded archive and place the models/ directory directly into the root of the project workspace:

    models/
    ├── digitization_models/
    │ ├── yolo11_full/weights/best.pt
    │ ├── yolo11_lead/weights/best.pt
    │ ├── yolo11_pulse/weights/best.pt
    │ └── yolo11_patch/weights/best.pt
    └── classifier_models/
    ├── mi_vs_normal_segmented/
    ├── omi_vs_nonomi/
    └── ecg_surgery/
    
  4. Launch the Web Dashboard Workstation:

    streamlit run app.py

🧠 Pre-Trained Classifiers & Tasks

The classification engine supports three distinct diagnostic tasks using the pre-trained weights in models/classifier_models/:

Diagnostic TaskModel ArchitectureExpected Input Tensor ShapeTest AccuracyTarget Positive Class
Normal vs Myocardial Infarction (MI)Arsenal Ensemble12 leads $ imes$ 140 timesteps92.3%MYOCARDIAL_INFARCTION
Occlusive MI (OMI) vs Non-OMIRocket Classifier12 leads $ imes$ 141 timesteps88.9%OMI
Pre-Procedural vs Post-Procedural MIInceptionTime Deep Net12 leads $ imes$ 140 timesteps91.4%pre-procedural MI
  • Arsenal: An ensemble of ROCKET classifiers utilizing random convolutional kernels combined with ridge regression feature classification.
  • Rocket: Random Omni-directional Kernel Extraction classifier computing high-dimensional time-series representations.
  • InceptionTime: A deep 1D convolutional neural network ensemble leveraging multi-scale temporal kernel convolutions.

🚀 Command Line Usage

Batch Signal Digitization (run_org.py)

Process structured directories of paper ECG scans in batch mode:

  1. Configure dataset directory paths in run_org.py:

    ORGANIZED_DIR="../ecg_files/ECG_organized_all"# Input dataset rootOUTPUT_DIR="../ecg_files/ECG_digitized"# Destination for CSVsCATEGORIES= ["pre", "index", "post"] # Sub-directories
  2. Run the batch digitization script:

    python run_org.py

Command-Line Model Inference (run_inference.py)

Run standalone inference on pre-digitized CSV datasets:

# 1. Normal vs MI Classification (Arsenal Model)
python archive/classification/run_inference.py --model mi_vs_normal_segmented --input data/ptb_xl/segmented_heartbeats.csv
# 2. Occlusive MI (OMI) vs Non-OMI Classification (Rocket Model)
python archive/classification/run_inference.py --model omi_vs_nonomi --input data/ecg_matrix_omi_segmented_50_150_90.csv
# 3. Custom Output Destination
python archive/classification/run_inference.py --model ecg_surgery --input data/ecg_surgery_segmented_50_150_70.csv --output results/surgery_preds.csv

📁 Repository Structure & Directory Organization

.
├── app.py # Streamlit application main router
├── config.py # Centralized configuration and model registry
├── digitization.py # Core ECGImage extraction pipeline class
├── environment.yml # Conda environment dependency specification
├── LICENSE # Non-commercial academic license agreement
├── README.md # Repository documentation
│
├── backend/ # Dashboard background execution adapters
│ ├── __init__.py # Package initializer
│ ├── digitization_runner.py # YOLO loader and single-image processor
│ └── classification_runner.py # Model loader and inference adapter
│
├── utils/ # Streamlit front-end UI view components
│ ├── __init__.py # Package initializer
│ ├── branding.py # Header titles and institutional footer logos
│ ├── css.py # Custom clinical theme and styling utilities
│ ├── hardware.py # Hardware detector (CPU/GPU)
│ ├── page_digitizer.py # ECG Digitizer page view
│ ├── page_csv_viewer.py # Interactive Signal Viewer page view
│ └── page_classifier.py # Classification workstation page view
│
├── models/ # Relocated YOLO checkpoints and classifiers (external)
│ ├── digitization_models/ # YOLOv11 weights (full, lead, pulse, patch)
│ └── classifier_models/ # Pre-trained classifier weights (Arsenal, Rocket, InceptionTime)
│
└── archive/ # Archived research, training, and CLI scripts (local)
└── classification/ # Baseline training and evaluation scripts

📷 How It Works: Signal Digitization

The core engine in digitization.py executes a multi-stage computer vision workflow to convert image pixels into calibrated voltage waveforms:

graph TD
A[ECG Image Upload] --> B[Preprocessing: Otsu & Blurring]
B --> C[YOLOv11 Detection & Segmentation]
subgraph YOLOv11 Models
C1[yolo11_full: Lead Boundaries]
C2[yolo11_lead: Text Name Labels]
C3[yolo11_pulse: Calibration Pulses]
C4[yolo11_patch: Waveform Segments]
end
C --> C1 & C2 & C3 & C4
C1 & C2 & C3 & C4 --> D[Hough Lines Calibration]
D --> E[K-Means Row & Column Grid Construction]
E --> F[Anti-Leakage Connected Components Filter]
F --> G[Centroid Trace & Resampling to 500Hz]
G --> H[Export latest_digitized.csv]
Loading
  1. Image Preprocessing: Cleans input scans using shadow removal, Otsu binarization, and Gaussian blurring to separate ink traces from paper texture.
  2. YOLO Segmentation: Applies patched YOLO segmentation models across multiple crop scales (, 4.5×, ) to bound individual lead regions.
  3. Multi-Model Object Detection: Runs YOLO detectors in parallel:
    • yolo11_full: Bounding boxes for the 12 lead channels.
    • yolo11_lead: Text label identification (I, II, aVR, V1-V6).
    • yolo11_pulse: Bounding boxes for 1 mV calibration reference pulses.
  4. Scale Calibration: Fits Hough lines to calibration pulse boundaries to compute exact voltage scaling ($ ext{V}/ ext{px}$) and time scaling ($ ext{s}/ ext{px}$).
  5. Grid Construction: Employs K-Means clustering on lead coordinates to construct regular grid layouts (3×4, 4×3, 6×2, 12×1) and resolve standard Cabrera lead ordering.
  6. Contour Tracing & Anti-Leakage Filtering: Traces pixel centroids, baseline-corrects waveforms, and applies an anti-leakage connected-component filter per crop to isolate primary waveform traces from adjacent lead leakage. Signals are resampled to 500 Hz calibrated in mV.

📈 How It Works: Signal Analysis & Visualization

graph TD
A[Upload Digitized CSV] --> B[Parse Lead Voltages & Timestamps]
B --> C[Vega-Lite Interactive Visualizer]
C --> C1[Render Stacked Leads]
C --> C2[Render Overlaid Signals]
B --> D[Compute Signal Statistics: Mean, SD, Min/Max]
D --> E[Display Summary Dataframes & Row Previews]
Loading
  1. Signal Parsing: Validates multi-lead CSV headers, timestamps, and sampling consistency.
  2. Interactive Rendering: Native Vega-Lite charts enable client-side pan, zoom, and multi-channel hover tooltips.
  3. Statistical Profiling: Calculates lead-level statistical metrics (mean, standard deviation, voltage range, min/max).

⚡ How It Works: Heartbeat Segmentation

Prepares continuous 12-lead signals for classification models via Pan-Tompkins R-peak detection:

graph TD
A[Digitized 500Hz Signal] --> B[Bandpass Filter 5-15Hz]
B --> C[Derivative Filter]
C --> D[Squaring Operation]
D --> E[Moving Window Integration]
E --> F[Adaptive Thresholding & R-Peak Search]
F --> G[Extract 140-sample Beats: 50ms pre-R, 150ms post-R]
G --> H[Max-Absolute Voltage Normalization]
Loading
  1. Bandpass Filtering: 5–15 Hz bandpass filter isolates QRS energy while suppressing muscle artifact and baseline wander.
  2. Differentiation & Squaring: Highlights steep QRS slopes and attenuates P/T waves.
  3. Moving Window Integration: Integrates energy across a 150 ms window to delineate QRS complexes.
  4. Adaptive Thresholding: Dynamically searches for R-peak maxima.
  5. Beat Windowing & Normalization: Extracts beat windows centered around R-peaks (50 ms pre-R, 150 ms post-R), normalizes max-absolute voltage, and formats output tensors (140/141 timesteps).

🧠 How It Works: Cardiac Classification

graph TD
A[Segmented Heartbeats] --> B[Numpy3D Reshaping: N_instances × 12_leads × N_timesteps]
B --> C[Select Classification Task]
subgraph Model Registry
C1[Normal vs MI: Arsenal]
C2[OMI vs non-OMI: Rocket]
C3[Pre vs Post-Procedural MI: InceptionTime]
end
C --> C1 & C2 & C3
C1 & C2 & C3 --> D[Load Pre-Trained Pickled Estimator]
D --> E[Predict Class Labels & Probabilities]
E --> F[Generate Downloadable Predictions CSV]
Loading
  1. Tensor Formatting: Formats heartbeat segments into 3D NumPy arrays (N_samples, 12_leads, N_timesteps).
  2. Model Evaluation: Invokes the pre-trained pickled estimator for the selected diagnostic endpoint.
  3. Report Generation: Formats class predictions, confidence probabilities, and diagnostic metrics for export.

🤝 Collaborating Institutions

This research project was developed in multi-center academic and clinical collaboration:

ETH ZürichIstituto Cardiocentro Ticino (EOC)USIUniversità della Campania Luigi Vanvitelli


👥 Authors & Contact

  • Shreyasvi Natrajsnatraj@ethz.ch
  • Cyrus Achtari
  • Felice Gragnano
  • Andrea Milzi
  • Marco Valgimigli
  • Diego Paez-Granados

📄 Citation

If you use ECGLight or its pre-trained models in your research, please cite our arXiv preprint:

@article{natraj2026ecglight,
title={ECGLight: Compute-Light Framework For Paper ECG Digitization and Myocardial Infarction Screening},
author={Natraj, Shreyasvi and Achtari, Cyrus and Gragnano, Felice and Milzi, Andrea and Valgimigli, Marco and Paez-Granados, Diego},
journal={arXiv preprint arXiv:2607.07683},
year={2026},
url={https://arxiv.org/abs/2607.07683},
doi={10.48550/arXiv.2607.07683}
}

APA Citation: Natraj, S., Achtari, C., Gragnano, F., Milzi, A., Valgimigli, M., & Paez-Granados, D. (2026). ECGLight: Compute-Light Framework For Paper ECG Digitization and Myocardial Infarction Screening. arXiv preprint arXiv:2607.07683. https://arxiv.org/abs/2607.07683


📄 License

This repository and model weights are released under the Non-Commercial Academic and Research License Agreement. Please refer to the LICENSE file for full terms. Free for non-profit academic and research use. Commercial use is strictly prohibited.

About

Directory containing the backend and front end of Paper ECG Digitization and Classification

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

⚡ ECGLight: Compute-Light Framework for Paper ECG Digitization & Myocardial Infarction Screening

arXivPython 3.9+PyTorchUltralytics YOLOv11Streamlit WorkstationLicense: Non-Commercial


📌 Abstract & Key Highlights

ECGLight is an end-to-end, compute-light framework and interactive web workstation for converting paper/photographed 12-lead ECG records into high-fidelity 500 Hz digitized signals and performing automated screening for Myocardial Infarction (MI) and Occlusive MI (OMI) pathologies.

💡 Designed for Low-Resource & Remote Settings: ECGLight runs completely on CPU-only hardware in <30 seconds per ECG without requiring cloud connectivity or expensive GPU infrastructure, democratizing AI-based decision support for clinics worldwide.

✨ Key Features & Capabilities

  • 📷 High-Fidelity Signal Digitization: Multi-stage computer vision pipeline combining sequential YOLOv11 object detection, scale calibration via Hough lines, K-Means grid construction, and an anti-leakage connected-component filter to extract clean 500 Hz 12-lead signals from smartphone photos or scans.
  • ❤️ High-Accuracy MI & OMI Screening:
    • 95.51% Accuracy ($F_1 = 0.9519$) for MI detection on the benchmark PTB-XL dataset (21,799 ECGs).
    • 88.89% Accuracy ($F_1 = 0.8862$) for Occlusive MI (OMI) screening on the hospital-acquired ECG-Matrix dataset.
  • ⚡ On-Device & Resource-Efficient: Fully functional on standard consumer laptop CPUs or CUDA GPUs.
  • 🖥️ Interactive Web Dashboard Workstation: Streamlit workstation featuring real-time signal viewing, step-by-step digitization previews, R-peak beat segmentation, and downloadable diagnostic prediction tables.

📰 News & Updates


📌 Table of Contents


🖥️ Web Dashboard Workstation Overview

The ECGLight workstation provides a responsive user interface designed for clinical workflow exploration, research, and education. It unifies the computer vision digitization and diagnostic classification models into a seamless local web application.

Workstation Modules

  1. 📷 ECG Image Digitizer:

    • Upload scanned or photographed ECG images (.png, .jpg, .jpeg).
    • Execute the sequential YOLOv11 detection pipeline with real-time visual progress indicators.
    • Summarizes detected leads, calibrated sampling rates, and total extracted samples.
    • Automatically exports the digitized time-series CSV to output/digitization/latest_digitized.csv.
  2. 📈 ECG Signal Viewer:

    • Interactive multi-channel ECG signal visualization using native Streamlit/Vega-Lite charts with zoom, pan, and hover tooltips.
    • Supports stacked subplots (with distinct clinical lead colorings) and multi-lead overlay modes.
    • Computes statistical summaries (mean, SD, min/max, voltage range) and row-level previewing.
  3. ❤️ ECG Classification Engine:

    • Evaluates cardiac pathologies using pre-trained time-series ensemble and deep learning classifiers.
    • Automatically segments raw signals into heartbeats around R-peaks using the Pan-Tompkins algorithm.
    • Inference Mode (Unlabeled Data): Generates downloadable Predictions Tables with predicted class labels and probability confidence scores.
    • Evaluation Mode (Ground-Truth Labeled Data): Displays interactive evaluation metrics (Accuracy, $F_1$-Score, Sensitivity, Specificity, Confusion Matrix).

🔄 End-to-End Workflow

The pipeline operates in four coordinated phases: Digitization $ ightarrow$ Analysis $ ightarrow$ Segmentation $ ightarrow$ Classification. Architectural flowcharts for each phase are provided in the How It Works sections below.


🚀 Installation & Setup

Prerequisites

  • Python: 3.9+ (tested on Python 3.9 and 3.11)
  • Hardware: Standard CPU (CUDA-capable GPU optional, automatically detected)

Step-by-Step Installation

  1. Clone the Repository:

    git clone https://github.com/scai-lab/ECG-Digitization-Classification.git
    cd ECG-Digitization-Classification
  2. Create and Activate Conda Environment:

    conda env create -f environment.yml
    conda activate infer

    [!IMPORTANT] Windows Compatibility & TensorFlow Setup: If running on Windows and encountering DLL loading errors (ImportError: DLL load failed while importing _pywrap_tensorflow_internal), install the pinned TensorFlow and Protobuf pairing:

    pip install tensorflow==2.15.0 protobuf==4.25.3
  3. Download Pre-Trained Model Weights: The YOLOv11 detection checkpoints and pre-trained time-series classifiers are hosted on Polybox due to file size constraints:

    👉 Download Pre-Trained Models Directory (ETH Zürich Polybox)

    Extract the downloaded archive and place the models/ directory directly into the root of the project workspace:

    models/
    ├── digitization_models/
    │ ├── yolo11_full/weights/best.pt
    │ ├── yolo11_lead/weights/best.pt
    │ ├── yolo11_pulse/weights/best.pt
    │ └── yolo11_patch/weights/best.pt
    └── classifier_models/
    ├── mi_vs_normal_segmented/
    ├── omi_vs_nonomi/
    └── ecg_surgery/
    
  4. Launch the Web Dashboard Workstation:

    streamlit run app.py

🧠 Pre-Trained Classifiers & Tasks

The classification engine supports three distinct diagnostic tasks using the pre-trained weights in models/classifier_models/:

Diagnostic TaskModel ArchitectureExpected Input Tensor ShapeTest AccuracyTarget Positive Class
Normal vs Myocardial Infarction (MI)Arsenal Ensemble12 leads $ imes$ 140 timesteps92.3%MYOCARDIAL_INFARCTION
Occlusive MI (OMI) vs Non-OMIRocket Classifier12 leads $ imes$ 141 timesteps88.9%OMI
Pre-Procedural vs Post-Procedural MIInceptionTime Deep Net12 leads $ imes$ 140 timesteps91.4%pre-procedural MI
  • Arsenal: An ensemble of ROCKET classifiers utilizing random convolutional kernels combined with ridge regression feature classification.
  • Rocket: Random Omni-directional Kernel Extraction classifier computing high-dimensional time-series representations.
  • InceptionTime: A deep 1D convolutional neural network ensemble leveraging multi-scale temporal kernel convolutions.

🚀 Command Line Usage

Batch Signal Digitization (run_org.py)

Process structured directories of paper ECG scans in batch mode:

  1. Configure dataset directory paths in run_org.py:

    ORGANIZED_DIR="../ecg_files/ECG_organized_all"# Input dataset rootOUTPUT_DIR="../ecg_files/ECG_digitized"# Destination for CSVsCATEGORIES= ["pre", "index", "post"] # Sub-directories
  2. Run the batch digitization script:

    python run_org.py

Command-Line Model Inference (run_inference.py)

Run standalone inference on pre-digitized CSV datasets:

# 1. Normal vs MI Classification (Arsenal Model)
python archive/classification/run_inference.py --model mi_vs_normal_segmented --input data/ptb_xl/segmented_heartbeats.csv
# 2. Occlusive MI (OMI) vs Non-OMI Classification (Rocket Model)
python archive/classification/run_inference.py --model omi_vs_nonomi --input data/ecg_matrix_omi_segmented_50_150_90.csv
# 3. Custom Output Destination
python archive/classification/run_inference.py --model ecg_surgery --input data/ecg_surgery_segmented_50_150_70.csv --output results/surgery_preds.csv

📁 Repository Structure & Directory Organization

.
├── app.py # Streamlit application main router
├── config.py # Centralized configuration and model registry
├── digitization.py # Core ECGImage extraction pipeline class
├── environment.yml # Conda environment dependency specification
├── LICENSE # Non-commercial academic license agreement
├── README.md # Repository documentation
│
├── backend/ # Dashboard background execution adapters
│ ├── __init__.py # Package initializer
│ ├── digitization_runner.py # YOLO loader and single-image processor
│ └── classification_runner.py # Model loader and inference adapter
│
├── utils/ # Streamlit front-end UI view components
│ ├── __init__.py # Package initializer
│ ├── branding.py # Header titles and institutional footer logos
│ ├── css.py # Custom clinical theme and styling utilities
│ ├── hardware.py # Hardware detector (CPU/GPU)
│ ├── page_digitizer.py # ECG Digitizer page view
│ ├── page_csv_viewer.py # Interactive Signal Viewer page view
│ └── page_classifier.py # Classification workstation page view
│
├── models/ # Relocated YOLO checkpoints and classifiers (external)
│ ├── digitization_models/ # YOLOv11 weights (full, lead, pulse, patch)
│ └── classifier_models/ # Pre-trained classifier weights (Arsenal, Rocket, InceptionTime)
│
└── archive/ # Archived research, training, and CLI scripts (local)
└── classification/ # Baseline training and evaluation scripts

📷 How It Works: Signal Digitization

The core engine in digitization.py executes a multi-stage computer vision workflow to convert image pixels into calibrated voltage waveforms:

graph TD
A[ECG Image Upload] --> B[Preprocessing: Otsu & Blurring]
B --> C[YOLOv11 Detection & Segmentation]
subgraph YOLOv11 Models
C1[yolo11_full: Lead Boundaries]
C2[yolo11_lead: Text Name Labels]
C3[yolo11_pulse: Calibration Pulses]
C4[yolo11_patch: Waveform Segments]
end
C --> C1 & C2 & C3 & C4
C1 & C2 & C3 & C4 --> D[Hough Lines Calibration]
D --> E[K-Means Row & Column Grid Construction]
E --> F[Anti-Leakage Connected Components Filter]
F --> G[Centroid Trace & Resampling to 500Hz]
G --> H[Export latest_digitized.csv]
Loading
  1. Image Preprocessing: Cleans input scans using shadow removal, Otsu binarization, and Gaussian blurring to separate ink traces from paper texture.
  2. YOLO Segmentation: Applies patched YOLO segmentation models across multiple crop scales (, 4.5×, ) to bound individual lead regions.
  3. Multi-Model Object Detection: Runs YOLO detectors in parallel:
    • yolo11_full: Bounding boxes for the 12 lead channels.
    • yolo11_lead: Text label identification (I, II, aVR, V1-V6).
    • yolo11_pulse: Bounding boxes for 1 mV calibration reference pulses.
  4. Scale Calibration: Fits Hough lines to calibration pulse boundaries to compute exact voltage scaling ($ ext{V}/ ext{px}$) and time scaling ($ ext{s}/ ext{px}$).
  5. Grid Construction: Employs K-Means clustering on lead coordinates to construct regular grid layouts (3×4, 4×3, 6×2, 12×1) and resolve standard Cabrera lead ordering.
  6. Contour Tracing & Anti-Leakage Filtering: Traces pixel centroids, baseline-corrects waveforms, and applies an anti-leakage connected-component filter per crop to isolate primary waveform traces from adjacent lead leakage. Signals are resampled to 500 Hz calibrated in mV.

📈 How It Works: Signal Analysis & Visualization

graph TD
A[Upload Digitized CSV] --> B[Parse Lead Voltages & Timestamps]
B --> C[Vega-Lite Interactive Visualizer]
C --> C1[Render Stacked Leads]
C --> C2[Render Overlaid Signals]
B --> D[Compute Signal Statistics: Mean, SD, Min/Max]
D --> E[Display Summary Dataframes & Row Previews]
Loading
  1. Signal Parsing: Validates multi-lead CSV headers, timestamps, and sampling consistency.
  2. Interactive Rendering: Native Vega-Lite charts enable client-side pan, zoom, and multi-channel hover tooltips.
  3. Statistical Profiling: Calculates lead-level statistical metrics (mean, standard deviation, voltage range, min/max).

⚡ How It Works: Heartbeat Segmentation

Prepares continuous 12-lead signals for classification models via Pan-Tompkins R-peak detection:

graph TD
A[Digitized 500Hz Signal] --> B[Bandpass Filter 5-15Hz]
B --> C[Derivative Filter]
C --> D[Squaring Operation]
D --> E[Moving Window Integration]
E --> F[Adaptive Thresholding & R-Peak Search]
F --> G[Extract 140-sample Beats: 50ms pre-R, 150ms post-R]
G --> H[Max-Absolute Voltage Normalization]
Loading
  1. Bandpass Filtering: 5–15 Hz bandpass filter isolates QRS energy while suppressing muscle artifact and baseline wander.
  2. Differentiation & Squaring: Highlights steep QRS slopes and attenuates P/T waves.
  3. Moving Window Integration: Integrates energy across a 150 ms window to delineate QRS complexes.
  4. Adaptive Thresholding: Dynamically searches for R-peak maxima.
  5. Beat Windowing & Normalization: Extracts beat windows centered around R-peaks (50 ms pre-R, 150 ms post-R), normalizes max-absolute voltage, and formats output tensors (140/141 timesteps).

🧠 How It Works: Cardiac Classification

graph TD
A[Segmented Heartbeats] --> B[Numpy3D Reshaping: N_instances × 12_leads × N_timesteps]
B --> C[Select Classification Task]
subgraph Model Registry
C1[Normal vs MI: Arsenal]
C2[OMI vs non-OMI: Rocket]
C3[Pre vs Post-Procedural MI: InceptionTime]
end
C --> C1 & C2 & C3
C1 & C2 & C3 --> D[Load Pre-Trained Pickled Estimator]
D --> E[Predict Class Labels & Probabilities]
E --> F[Generate Downloadable Predictions CSV]
Loading
  1. Tensor Formatting: Formats heartbeat segments into 3D NumPy arrays (N_samples, 12_leads, N_timesteps).
  2. Model Evaluation: Invokes the pre-trained pickled estimator for the selected diagnostic endpoint.
  3. Report Generation: Formats class predictions, confidence probabilities, and diagnostic metrics for export.

🤝 Collaborating Institutions

This research project was developed in multi-center academic and clinical collaboration:

ETH ZürichIstituto Cardiocentro Ticino (EOC)USIUniversità della Campania Luigi Vanvitelli


👥 Authors & Contact

  • Shreyasvi Natrajsnatraj@ethz.ch
  • Cyrus Achtari
  • Felice Gragnano
  • Andrea Milzi
  • Marco Valgimigli
  • Diego Paez-Granados

📄 Citation

If you use ECGLight or its pre-trained models in your research, please cite our arXiv preprint:

@article{natraj2026ecglight,
title={ECGLight: Compute-Light Framework For Paper ECG Digitization and Myocardial Infarction Screening},
author={Natraj, Shreyasvi and Achtari, Cyrus and Gragnano, Felice and Milzi, Andrea and Valgimigli, Marco and Paez-Granados, Diego},
journal={arXiv preprint arXiv:2607.07683},
year={2026},
url={https://arxiv.org/abs/2607.07683},
doi={10.48550/arXiv.2607.07683}
}

APA Citation: Natraj, S., Achtari, C., Gragnano, F., Milzi, A., Valgimigli, M., & Paez-Granados, D. (2026). ECGLight: Compute-Light Framework For Paper ECG Digitization and Myocardial Infarction Screening. arXiv preprint arXiv:2607.07683. https://arxiv.org/abs/2607.07683


📄 License

This repository and model weights are released under the Non-Commercial Academic and Research License Agreement. Please refer to the LICENSE file for full terms. Free for non-profit academic and research use. Commercial use is strictly prohibited.

About

Directory containing the backend and front end of Paper ECG Digitization and Classification

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

⚡ ECGLight: Compute-Light Framework for Paper ECG Digitization & Myocardial Infarction Screening

arXivPython 3.9+PyTorchUltralytics YOLOv11Streamlit WorkstationLicense: Non-Commercial


📌 Abstract & Key Highlights

ECGLight is an end-to-end, compute-light framework and interactive web workstation for converting paper/photographed 12-lead ECG records into high-fidelity 500 Hz digitized signals and performing automated screening for Myocardial Infarction (MI) and Occlusive MI (OMI) pathologies.

💡 Designed for Low-Resource & Remote Settings: ECGLight runs completely on CPU-only hardware in <30 seconds per ECG without requiring cloud connectivity or expensive GPU infrastructure, democratizing AI-based decision support for clinics worldwide.

✨ Key Features & Capabilities

  • 📷 High-Fidelity Signal Digitization: Multi-stage computer vision pipeline combining sequential YOLOv11 object detection, scale calibration via Hough lines, K-Means grid construction, and an anti-leakage connected-component filter to extract clean 500 Hz 12-lead signals from smartphone photos or scans.
  • ❤️ High-Accuracy MI & OMI Screening:
    • 95.51% Accuracy ($F_1 = 0.9519$) for MI detection on the benchmark PTB-XL dataset (21,799 ECGs).
    • 88.89% Accuracy ($F_1 = 0.8862$) for Occlusive MI (OMI) screening on the hospital-acquired ECG-Matrix dataset.
  • ⚡ On-Device & Resource-Efficient: Fully functional on standard consumer laptop CPUs or CUDA GPUs.
  • 🖥️ Interactive Web Dashboard Workstation: Streamlit workstation featuring real-time signal viewing, step-by-step digitization previews, R-peak beat segmentation, and downloadable diagnostic prediction tables.

📰 News & Updates


📌 Table of Contents


🖥️ Web Dashboard Workstation Overview

The ECGLight workstation provides a responsive user interface designed for clinical workflow exploration, research, and education. It unifies the computer vision digitization and diagnostic classification models into a seamless local web application.

Workstation Modules

  1. 📷 ECG Image Digitizer:

    • Upload scanned or photographed ECG images (.png, .jpg, .jpeg).
    • Execute the sequential YOLOv11 detection pipeline with real-time visual progress indicators.
    • Summarizes detected leads, calibrated sampling rates, and total extracted samples.
    • Automatically exports the digitized time-series CSV to output/digitization/latest_digitized.csv.
  2. 📈 ECG Signal Viewer:

    • Interactive multi-channel ECG signal visualization using native Streamlit/Vega-Lite charts with zoom, pan, and hover tooltips.
    • Supports stacked subplots (with distinct clinical lead colorings) and multi-lead overlay modes.
    • Computes statistical summaries (mean, SD, min/max, voltage range) and row-level previewing.
  3. ❤️ ECG Classification Engine:

    • Evaluates cardiac pathologies using pre-trained time-series ensemble and deep learning classifiers.
    • Automatically segments raw signals into heartbeats around R-peaks using the Pan-Tompkins algorithm.
    • Inference Mode (Unlabeled Data): Generates downloadable Predictions Tables with predicted class labels and probability confidence scores.
    • Evaluation Mode (Ground-Truth Labeled Data): Displays interactive evaluation metrics (Accuracy, $F_1$-Score, Sensitivity, Specificity, Confusion Matrix).

🔄 End-to-End Workflow

The pipeline operates in four coordinated phases: Digitization $ ightarrow$ Analysis $ ightarrow$ Segmentation $ ightarrow$ Classification. Architectural flowcharts for each phase are provided in the How It Works sections below.


🚀 Installation & Setup

Prerequisites

  • Python: 3.9+ (tested on Python 3.9 and 3.11)
  • Hardware: Standard CPU (CUDA-capable GPU optional, automatically detected)

Step-by-Step Installation

  1. Clone the Repository:

    git clone https://github.com/scai-lab/ECG-Digitization-Classification.git
    cd ECG-Digitization-Classification
  2. Create and Activate Conda Environment:

    conda env create -f environment.yml
    conda activate infer

    [!IMPORTANT] Windows Compatibility & TensorFlow Setup: If running on Windows and encountering DLL loading errors (ImportError: DLL load failed while importing _pywrap_tensorflow_internal), install the pinned TensorFlow and Protobuf pairing:

    pip install tensorflow==2.15.0 protobuf==4.25.3
  3. Download Pre-Trained Model Weights: The YOLOv11 detection checkpoints and pre-trained time-series classifiers are hosted on Polybox due to file size constraints:

    👉 Download Pre-Trained Models Directory (ETH Zürich Polybox)

    Extract the downloaded archive and place the models/ directory directly into the root of the project workspace:

    models/
    ├── digitization_models/
    │ ├── yolo11_full/weights/best.pt
    │ ├── yolo11_lead/weights/best.pt
    │ ├── yolo11_pulse/weights/best.pt
    │ └── yolo11_patch/weights/best.pt
    └── classifier_models/
    ├── mi_vs_normal_segmented/
    ├── omi_vs_nonomi/
    └── ecg_surgery/
    
  4. Launch the Web Dashboard Workstation:

    streamlit run app.py

🧠 Pre-Trained Classifiers & Tasks

The classification engine supports three distinct diagnostic tasks using the pre-trained weights in models/classifier_models/:

Diagnostic TaskModel ArchitectureExpected Input Tensor ShapeTest AccuracyTarget Positive Class
Normal vs Myocardial Infarction (MI)Arsenal Ensemble12 leads $ imes$ 140 timesteps92.3%MYOCARDIAL_INFARCTION
Occlusive MI (OMI) vs Non-OMIRocket Classifier12 leads $ imes$ 141 timesteps88.9%OMI
Pre-Procedural vs Post-Procedural MIInceptionTime Deep Net12 leads $ imes$ 140 timesteps91.4%pre-procedural MI
  • Arsenal: An ensemble of ROCKET classifiers utilizing random convolutional kernels combined with ridge regression feature classification.
  • Rocket: Random Omni-directional Kernel Extraction classifier computing high-dimensional time-series representations.
  • InceptionTime: A deep 1D convolutional neural network ensemble leveraging multi-scale temporal kernel convolutions.

🚀 Command Line Usage

Batch Signal Digitization (run_org.py)

Process structured directories of paper ECG scans in batch mode:

  1. Configure dataset directory paths in run_org.py:

    ORGANIZED_DIR="../ecg_files/ECG_organized_all"# Input dataset rootOUTPUT_DIR="../ecg_files/ECG_digitized"# Destination for CSVsCATEGORIES= ["pre", "index", "post"] # Sub-directories
  2. Run the batch digitization script:

    python run_org.py

Command-Line Model Inference (run_inference.py)

Run standalone inference on pre-digitized CSV datasets:

# 1. Normal vs MI Classification (Arsenal Model)
python archive/classification/run_inference.py --model mi_vs_normal_segmented --input data/ptb_xl/segmented_heartbeats.csv
# 2. Occlusive MI (OMI) vs Non-OMI Classification (Rocket Model)
python archive/classification/run_inference.py --model omi_vs_nonomi --input data/ecg_matrix_omi_segmented_50_150_90.csv
# 3. Custom Output Destination
python archive/classification/run_inference.py --model ecg_surgery --input data/ecg_surgery_segmented_50_150_70.csv --output results/surgery_preds.csv

📁 Repository Structure & Directory Organization

.
├── app.py # Streamlit application main router
├── config.py # Centralized configuration and model registry
├── digitization.py # Core ECGImage extraction pipeline class
├── environment.yml # Conda environment dependency specification
├── LICENSE # Non-commercial academic license agreement
├── README.md # Repository documentation
│
├── backend/ # Dashboard background execution adapters
│ ├── __init__.py # Package initializer
│ ├── digitization_runner.py # YOLO loader and single-image processor
│ └── classification_runner.py # Model loader and inference adapter
│
├── utils/ # Streamlit front-end UI view components
│ ├── __init__.py # Package initializer
│ ├── branding.py # Header titles and institutional footer logos
│ ├── css.py # Custom clinical theme and styling utilities
│ ├── hardware.py # Hardware detector (CPU/GPU)
│ ├── page_digitizer.py # ECG Digitizer page view
│ ├── page_csv_viewer.py # Interactive Signal Viewer page view
│ └── page_classifier.py # Classification workstation page view
│
├── models/ # Relocated YOLO checkpoints and classifiers (external)
│ ├── digitization_models/ # YOLOv11 weights (full, lead, pulse, patch)
│ └── classifier_models/ # Pre-trained classifier weights (Arsenal, Rocket, InceptionTime)
│
└── archive/ # Archived research, training, and CLI scripts (local)
└── classification/ # Baseline training and evaluation scripts

📷 How It Works: Signal Digitization

The core engine in digitization.py executes a multi-stage computer vision workflow to convert image pixels into calibrated voltage waveforms:

graph TD
A[ECG Image Upload] --> B[Preprocessing: Otsu & Blurring]
B --> C[YOLOv11 Detection & Segmentation]
subgraph YOLOv11 Models
C1[yolo11_full: Lead Boundaries]
C2[yolo11_lead: Text Name Labels]
C3[yolo11_pulse: Calibration Pulses]
C4[yolo11_patch: Waveform Segments]
end
C --> C1 & C2 & C3 & C4
C1 & C2 & C3 & C4 --> D[Hough Lines Calibration]
D --> E[K-Means Row & Column Grid Construction]
E --> F[Anti-Leakage Connected Components Filter]
F --> G[Centroid Trace & Resampling to 500Hz]
G --> H[Export latest_digitized.csv]
Loading
  1. Image Preprocessing: Cleans input scans using shadow removal, Otsu binarization, and Gaussian blurring to separate ink traces from paper texture.
  2. YOLO Segmentation: Applies patched YOLO segmentation models across multiple crop scales (, 4.5×, ) to bound individual lead regions.
  3. Multi-Model Object Detection: Runs YOLO detectors in parallel:
    • yolo11_full: Bounding boxes for the 12 lead channels.
    • yolo11_lead: Text label identification (I, II, aVR, V1-V6).
    • yolo11_pulse: Bounding boxes for 1 mV calibration reference pulses.
  4. Scale Calibration: Fits Hough lines to calibration pulse boundaries to compute exact voltage scaling ($ ext{V}/ ext{px}$) and time scaling ($ ext{s}/ ext{px}$).
  5. Grid Construction: Employs K-Means clustering on lead coordinates to construct regular grid layouts (3×4, 4×3, 6×2, 12×1) and resolve standard Cabrera lead ordering.
  6. Contour Tracing & Anti-Leakage Filtering: Traces pixel centroids, baseline-corrects waveforms, and applies an anti-leakage connected-component filter per crop to isolate primary waveform traces from adjacent lead leakage. Signals are resampled to 500 Hz calibrated in mV.

📈 How It Works: Signal Analysis & Visualization

graph TD
A[Upload Digitized CSV] --> B[Parse Lead Voltages & Timestamps]
B --> C[Vega-Lite Interactive Visualizer]
C --> C1[Render Stacked Leads]
C --> C2[Render Overlaid Signals]
B --> D[Compute Signal Statistics: Mean, SD, Min/Max]
D --> E[Display Summary Dataframes & Row Previews]
Loading
  1. Signal Parsing: Validates multi-lead CSV headers, timestamps, and sampling consistency.
  2. Interactive Rendering: Native Vega-Lite charts enable client-side pan, zoom, and multi-channel hover tooltips.
  3. Statistical Profiling: Calculates lead-level statistical metrics (mean, standard deviation, voltage range, min/max).

⚡ How It Works: Heartbeat Segmentation

Prepares continuous 12-lead signals for classification models via Pan-Tompkins R-peak detection:

graph TD
A[Digitized 500Hz Signal] --> B[Bandpass Filter 5-15Hz]
B --> C[Derivative Filter]
C --> D[Squaring Operation]
D --> E[Moving Window Integration]
E --> F[Adaptive Thresholding & R-Peak Search]
F --> G[Extract 140-sample Beats: 50ms pre-R, 150ms post-R]
G --> H[Max-Absolute Voltage Normalization]
Loading
  1. Bandpass Filtering: 5–15 Hz bandpass filter isolates QRS energy while suppressing muscle artifact and baseline wander.
  2. Differentiation & Squaring: Highlights steep QRS slopes and attenuates P/T waves.
  3. Moving Window Integration: Integrates energy across a 150 ms window to delineate QRS complexes.
  4. Adaptive Thresholding: Dynamically searches for R-peak maxima.
  5. Beat Windowing & Normalization: Extracts beat windows centered around R-peaks (50 ms pre-R, 150 ms post-R), normalizes max-absolute voltage, and formats output tensors (140/141 timesteps).

🧠 How It Works: Cardiac Classification

graph TD
A[Segmented Heartbeats] --> B[Numpy3D Reshaping: N_instances × 12_leads × N_timesteps]
B --> C[Select Classification Task]
subgraph Model Registry
C1[Normal vs MI: Arsenal]
C2[OMI vs non-OMI: Rocket]
C3[Pre vs Post-Procedural MI: InceptionTime]
end
C --> C1 & C2 & C3
C1 & C2 & C3 --> D[Load Pre-Trained Pickled Estimator]
D --> E[Predict Class Labels & Probabilities]
E --> F[Generate Downloadable Predictions CSV]
Loading
  1. Tensor Formatting: Formats heartbeat segments into 3D NumPy arrays (N_samples, 12_leads, N_timesteps).
  2. Model Evaluation: Invokes the pre-trained pickled estimator for the selected diagnostic endpoint.
  3. Report Generation: Formats class predictions, confidence probabilities, and diagnostic metrics for export.

🤝 Collaborating Institutions

This research project was developed in multi-center academic and clinical collaboration:

ETH ZürichIstituto Cardiocentro Ticino (EOC)USIUniversità della Campania Luigi Vanvitelli


👥 Authors & Contact

  • Shreyasvi Natrajsnatraj@ethz.ch
  • Cyrus Achtari
  • Felice Gragnano
  • Andrea Milzi
  • Marco Valgimigli
  • Diego Paez-Granados

📄 Citation

If you use ECGLight or its pre-trained models in your research, please cite our arXiv preprint:

@article{natraj2026ecglight,
title={ECGLight: Compute-Light Framework For Paper ECG Digitization and Myocardial Infarction Screening},
author={Natraj, Shreyasvi and Achtari, Cyrus and Gragnano, Felice and Milzi, Andrea and Valgimigli, Marco and Paez-Granados, Diego},
journal={arXiv preprint arXiv:2607.07683},
year={2026},
url={https://arxiv.org/abs/2607.07683},
doi={10.48550/arXiv.2607.07683}
}

APA Citation: Natraj, S., Achtari, C., Gragnano, F., Milzi, A., Valgimigli, M., & Paez-Granados, D. (2026). ECGLight: Compute-Light Framework For Paper ECG Digitization and Myocardial Infarction Screening. arXiv preprint arXiv:2607.07683. https://arxiv.org/abs/2607.07683


📄 License

This repository and model weights are released under the Non-Commercial Academic and Research License Agreement. Please refer to the LICENSE file for full terms. Free for non-profit academic and research use. Commercial use is strictly prohibited.

About

Directory containing the backend and front end of Paper ECG Digitization and Classification

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

⚡ ECGLight: Compute-Light Framework for Paper ECG Digitization & Myocardial Infarction Screening

arXivPython 3.9+PyTorchUltralytics YOLOv11Streamlit WorkstationLicense: Non-Commercial


📌 Abstract & Key Highlights

ECGLight is an end-to-end, compute-light framework and interactive web workstation for converting paper/photographed 12-lead ECG records into high-fidelity 500 Hz digitized signals and performing automated screening for Myocardial Infarction (MI) and Occlusive MI (OMI) pathologies.

💡 Designed for Low-Resource & Remote Settings: ECGLight runs completely on CPU-only hardware in <30 seconds per ECG without requiring cloud connectivity or expensive GPU infrastructure, democratizing AI-based decision support for clinics worldwide.

✨ Key Features & Capabilities

  • 📷 High-Fidelity Signal Digitization: Multi-stage computer vision pipeline combining sequential YOLOv11 object detection, scale calibration via Hough lines, K-Means grid construction, and an anti-leakage connected-component filter to extract clean 500 Hz 12-lead signals from smartphone photos or scans.
  • ❤️ High-Accuracy MI & OMI Screening:
    • 95.51% Accuracy ($F_1 = 0.9519$) for MI detection on the benchmark PTB-XL dataset (21,799 ECGs).
    • 88.89% Accuracy ($F_1 = 0.8862$) for Occlusive MI (OMI) screening on the hospital-acquired ECG-Matrix dataset.
  • ⚡ On-Device & Resource-Efficient: Fully functional on standard consumer laptop CPUs or CUDA GPUs.
  • 🖥️ Interactive Web Dashboard Workstation: Streamlit workstation featuring real-time signal viewing, step-by-step digitization previews, R-peak beat segmentation, and downloadable diagnostic prediction tables.

📰 News & Updates


📌 Table of Contents


🖥️ Web Dashboard Workstation Overview

The ECGLight workstation provides a responsive user interface designed for clinical workflow exploration, research, and education. It unifies the computer vision digitization and diagnostic classification models into a seamless local web application.

Workstation Modules

  1. 📷 ECG Image Digitizer:

    • Upload scanned or photographed ECG images (.png, .jpg, .jpeg).
    • Execute the sequential YOLOv11 detection pipeline with real-time visual progress indicators.
    • Summarizes detected leads, calibrated sampling rates, and total extracted samples.
    • Automatically exports the digitized time-series CSV to output/digitization/latest_digitized.csv.
  2. 📈 ECG Signal Viewer:

    • Interactive multi-channel ECG signal visualization using native Streamlit/Vega-Lite charts with zoom, pan, and hover tooltips.
    • Supports stacked subplots (with distinct clinical lead colorings) and multi-lead overlay modes.
    • Computes statistical summaries (mean, SD, min/max, voltage range) and row-level previewing.
  3. ❤️ ECG Classification Engine:

    • Evaluates cardiac pathologies using pre-trained time-series ensemble and deep learning classifiers.
    • Automatically segments raw signals into heartbeats around R-peaks using the Pan-Tompkins algorithm.
    • Inference Mode (Unlabeled Data): Generates downloadable Predictions Tables with predicted class labels and probability confidence scores.
    • Evaluation Mode (Ground-Truth Labeled Data): Displays interactive evaluation metrics (Accuracy, $F_1$-Score, Sensitivity, Specificity, Confusion Matrix).

🔄 End-to-End Workflow

The pipeline operates in four coordinated phases: Digitization $ ightarrow$ Analysis $ ightarrow$ Segmentation $ ightarrow$ Classification. Architectural flowcharts for each phase are provided in the How It Works sections below.


🚀 Installation & Setup

Prerequisites

  • Python: 3.9+ (tested on Python 3.9 and 3.11)
  • Hardware: Standard CPU (CUDA-capable GPU optional, automatically detected)

Step-by-Step Installation

  1. Clone the Repository:

    git clone https://github.com/scai-lab/ECG-Digitization-Classification.git
    cd ECG-Digitization-Classification
  2. Create and Activate Conda Environment:

    conda env create -f environment.yml
    conda activate infer

    [!IMPORTANT] Windows Compatibility & TensorFlow Setup: If running on Windows and encountering DLL loading errors (ImportError: DLL load failed while importing _pywrap_tensorflow_internal), install the pinned TensorFlow and Protobuf pairing:

    pip install tensorflow==2.15.0 protobuf==4.25.3
  3. Download Pre-Trained Model Weights: The YOLOv11 detection checkpoints and pre-trained time-series classifiers are hosted on Polybox due to file size constraints:

    👉 Download Pre-Trained Models Directory (ETH Zürich Polybox)

    Extract the downloaded archive and place the models/ directory directly into the root of the project workspace:

    models/
    ├── digitization_models/
    │ ├── yolo11_full/weights/best.pt
    │ ├── yolo11_lead/weights/best.pt
    │ ├── yolo11_pulse/weights/best.pt
    │ └── yolo11_patch/weights/best.pt
    └── classifier_models/
    ├── mi_vs_normal_segmented/
    ├── omi_vs_nonomi/
    └── ecg_surgery/
    
  4. Launch the Web Dashboard Workstation:

    streamlit run app.py

🧠 Pre-Trained Classifiers & Tasks

The classification engine supports three distinct diagnostic tasks using the pre-trained weights in models/classifier_models/:

Diagnostic TaskModel ArchitectureExpected Input Tensor ShapeTest AccuracyTarget Positive Class
Normal vs Myocardial Infarction (MI)Arsenal Ensemble12 leads $ imes$ 140 timesteps92.3%MYOCARDIAL_INFARCTION
Occlusive MI (OMI) vs Non-OMIRocket Classifier12 leads $ imes$ 141 timesteps88.9%OMI
Pre-Procedural vs Post-Procedural MIInceptionTime Deep Net12 leads $ imes$ 140 timesteps91.4%pre-procedural MI
  • Arsenal: An ensemble of ROCKET classifiers utilizing random convolutional kernels combined with ridge regression feature classification.
  • Rocket: Random Omni-directional Kernel Extraction classifier computing high-dimensional time-series representations.
  • InceptionTime: A deep 1D convolutional neural network ensemble leveraging multi-scale temporal kernel convolutions.

🚀 Command Line Usage

Batch Signal Digitization (run_org.py)

Process structured directories of paper ECG scans in batch mode:

  1. Configure dataset directory paths in run_org.py:

    ORGANIZED_DIR="../ecg_files/ECG_organized_all"# Input dataset rootOUTPUT_DIR="../ecg_files/ECG_digitized"# Destination for CSVsCATEGORIES= ["pre", "index", "post"] # Sub-directories
  2. Run the batch digitization script:

    python run_org.py

Command-Line Model Inference (run_inference.py)

Run standalone inference on pre-digitized CSV datasets:

# 1. Normal vs MI Classification (Arsenal Model)
python archive/classification/run_inference.py --model mi_vs_normal_segmented --input data/ptb_xl/segmented_heartbeats.csv
# 2. Occlusive MI (OMI) vs Non-OMI Classification (Rocket Model)
python archive/classification/run_inference.py --model omi_vs_nonomi --input data/ecg_matrix_omi_segmented_50_150_90.csv
# 3. Custom Output Destination
python archive/classification/run_inference.py --model ecg_surgery --input data/ecg_surgery_segmented_50_150_70.csv --output results/surgery_preds.csv

📁 Repository Structure & Directory Organization

.
├── app.py # Streamlit application main router
├── config.py # Centralized configuration and model registry
├── digitization.py # Core ECGImage extraction pipeline class
├── environment.yml # Conda environment dependency specification
├── LICENSE # Non-commercial academic license agreement
├── README.md # Repository documentation
│
├── backend/ # Dashboard background execution adapters
│ ├── __init__.py # Package initializer
│ ├── digitization_runner.py # YOLO loader and single-image processor
│ └── classification_runner.py # Model loader and inference adapter
│
├── utils/ # Streamlit front-end UI view components
│ ├── __init__.py # Package initializer
│ ├── branding.py # Header titles and institutional footer logos
│ ├── css.py # Custom clinical theme and styling utilities
│ ├── hardware.py # Hardware detector (CPU/GPU)
│ ├── page_digitizer.py # ECG Digitizer page view
│ ├── page_csv_viewer.py # Interactive Signal Viewer page view
│ └── page_classifier.py # Classification workstation page view
│
├── models/ # Relocated YOLO checkpoints and classifiers (external)
│ ├── digitization_models/ # YOLOv11 weights (full, lead, pulse, patch)
│ └── classifier_models/ # Pre-trained classifier weights (Arsenal, Rocket, InceptionTime)
│
└── archive/ # Archived research, training, and CLI scripts (local)
└── classification/ # Baseline training and evaluation scripts

📷 How It Works: Signal Digitization

The core engine in digitization.py executes a multi-stage computer vision workflow to convert image pixels into calibrated voltage waveforms:

graph TD
A[ECG Image Upload] --> B[Preprocessing: Otsu & Blurring]
B --> C[YOLOv11 Detection & Segmentation]
subgraph YOLOv11 Models
C1[yolo11_full: Lead Boundaries]
C2[yolo11_lead: Text Name Labels]
C3[yolo11_pulse: Calibration Pulses]
C4[yolo11_patch: Waveform Segments]
end
C --> C1 & C2 & C3 & C4
C1 & C2 & C3 & C4 --> D[Hough Lines Calibration]
D --> E[K-Means Row & Column Grid Construction]
E --> F[Anti-Leakage Connected Components Filter]
F --> G[Centroid Trace & Resampling to 500Hz]
G --> H[Export latest_digitized.csv]
Loading
  1. Image Preprocessing: Cleans input scans using shadow removal, Otsu binarization, and Gaussian blurring to separate ink traces from paper texture.
  2. YOLO Segmentation: Applies patched YOLO segmentation models across multiple crop scales (, 4.5×, ) to bound individual lead regions.
  3. Multi-Model Object Detection: Runs YOLO detectors in parallel:
    • yolo11_full: Bounding boxes for the 12 lead channels.
    • yolo11_lead: Text label identification (I, II, aVR, V1-V6).
    • yolo11_pulse: Bounding boxes for 1 mV calibration reference pulses.
  4. Scale Calibration: Fits Hough lines to calibration pulse boundaries to compute exact voltage scaling ($ ext{V}/ ext{px}$) and time scaling ($ ext{s}/ ext{px}$).
  5. Grid Construction: Employs K-Means clustering on lead coordinates to construct regular grid layouts (3×4, 4×3, 6×2, 12×1) and resolve standard Cabrera lead ordering.
  6. Contour Tracing & Anti-Leakage Filtering: Traces pixel centroids, baseline-corrects waveforms, and applies an anti-leakage connected-component filter per crop to isolate primary waveform traces from adjacent lead leakage. Signals are resampled to 500 Hz calibrated in mV.

📈 How It Works: Signal Analysis & Visualization

graph TD
A[Upload Digitized CSV] --> B[Parse Lead Voltages & Timestamps]
B --> C[Vega-Lite Interactive Visualizer]
C --> C1[Render Stacked Leads]
C --> C2[Render Overlaid Signals]
B --> D[Compute Signal Statistics: Mean, SD, Min/Max]
D --> E[Display Summary Dataframes & Row Previews]
Loading
  1. Signal Parsing: Validates multi-lead CSV headers, timestamps, and sampling consistency.
  2. Interactive Rendering: Native Vega-Lite charts enable client-side pan, zoom, and multi-channel hover tooltips.
  3. Statistical Profiling: Calculates lead-level statistical metrics (mean, standard deviation, voltage range, min/max).

⚡ How It Works: Heartbeat Segmentation

Prepares continuous 12-lead signals for classification models via Pan-Tompkins R-peak detection:

graph TD
A[Digitized 500Hz Signal] --> B[Bandpass Filter 5-15Hz]
B --> C[Derivative Filter]
C --> D[Squaring Operation]
D --> E[Moving Window Integration]
E --> F[Adaptive Thresholding & R-Peak Search]
F --> G[Extract 140-sample Beats: 50ms pre-R, 150ms post-R]
G --> H[Max-Absolute Voltage Normalization]
Loading
  1. Bandpass Filtering: 5–15 Hz bandpass filter isolates QRS energy while suppressing muscle artifact and baseline wander.
  2. Differentiation & Squaring: Highlights steep QRS slopes and attenuates P/T waves.
  3. Moving Window Integration: Integrates energy across a 150 ms window to delineate QRS complexes.
  4. Adaptive Thresholding: Dynamically searches for R-peak maxima.
  5. Beat Windowing & Normalization: Extracts beat windows centered around R-peaks (50 ms pre-R, 150 ms post-R), normalizes max-absolute voltage, and formats output tensors (140/141 timesteps).

🧠 How It Works: Cardiac Classification

graph TD
A[Segmented Heartbeats] --> B[Numpy3D Reshaping: N_instances × 12_leads × N_timesteps]
B --> C[Select Classification Task]
subgraph Model Registry
C1[Normal vs MI: Arsenal]
C2[OMI vs non-OMI: Rocket]
C3[Pre vs Post-Procedural MI: InceptionTime]
end
C --> C1 & C2 & C3
C1 & C2 & C3 --> D[Load Pre-Trained Pickled Estimator]
D --> E[Predict Class Labels & Probabilities]
E --> F[Generate Downloadable Predictions CSV]
Loading
  1. Tensor Formatting: Formats heartbeat segments into 3D NumPy arrays (N_samples, 12_leads, N_timesteps).
  2. Model Evaluation: Invokes the pre-trained pickled estimator for the selected diagnostic endpoint.
  3. Report Generation: Formats class predictions, confidence probabilities, and diagnostic metrics for export.

🤝 Collaborating Institutions

This research project was developed in multi-center academic and clinical collaboration:

ETH ZürichIstituto Cardiocentro Ticino (EOC)USIUniversità della Campania Luigi Vanvitelli


👥 Authors & Contact

  • Shreyasvi Natrajsnatraj@ethz.ch
  • Cyrus Achtari
  • Felice Gragnano
  • Andrea Milzi
  • Marco Valgimigli
  • Diego Paez-Granados

📄 Citation

If you use ECGLight or its pre-trained models in your research, please cite our arXiv preprint:

@article{natraj2026ecglight,
title={ECGLight: Compute-Light Framework For Paper ECG Digitization and Myocardial Infarction Screening},
author={Natraj, Shreyasvi and Achtari, Cyrus and Gragnano, Felice and Milzi, Andrea and Valgimigli, Marco and Paez-Granados, Diego},
journal={arXiv preprint arXiv:2607.07683},
year={2026},
url={https://arxiv.org/abs/2607.07683},
doi={10.48550/arXiv.2607.07683}
}

APA Citation: Natraj, S., Achtari, C., Gragnano, F., Milzi, A., Valgimigli, M., & Paez-Granados, D. (2026). ECGLight: Compute-Light Framework For Paper ECG Digitization and Myocardial Infarction Screening. arXiv preprint arXiv:2607.07683. https://arxiv.org/abs/2607.07683


📄 License

This repository and model weights are released under the Non-Commercial Academic and Research License Agreement. Please refer to the LICENSE file for full terms. Free for non-profit academic and research use. Commercial use is strictly prohibited.

About

Directory containing the backend and front end of Paper ECG Digitization and Classification

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

⚡ ECGLight: Compute-Light Framework for Paper ECG Digitization & Myocardial Infarction Screening

arXivPython 3.9+PyTorchUltralytics YOLOv11Streamlit WorkstationLicense: Non-Commercial


📌 Abstract & Key Highlights

ECGLight is an end-to-end, compute-light framework and interactive web workstation for converting paper/photographed 12-lead ECG records into high-fidelity 500 Hz digitized signals and performing automated screening for Myocardial Infarction (MI) and Occlusive MI (OMI) pathologies.

💡 Designed for Low-Resource & Remote Settings: ECGLight runs completely on CPU-only hardware in <30 seconds per ECG without requiring cloud connectivity or expensive GPU infrastructure, democratizing AI-based decision support for clinics worldwide.

✨ Key Features & Capabilities

  • 📷 High-Fidelity Signal Digitization: Multi-stage computer vision pipeline combining sequential YOLOv11 object detection, scale calibration via Hough lines, K-Means grid construction, and an anti-leakage connected-component filter to extract clean 500 Hz 12-lead signals from smartphone photos or scans.
  • ❤️ High-Accuracy MI & OMI Screening:
    • 95.51% Accuracy ($F_1 = 0.9519$) for MI detection on the benchmark PTB-XL dataset (21,799 ECGs).
    • 88.89% Accuracy ($F_1 = 0.8862$) for Occlusive MI (OMI) screening on the hospital-acquired ECG-Matrix dataset.
  • ⚡ On-Device & Resource-Efficient: Fully functional on standard consumer laptop CPUs or CUDA GPUs.
  • 🖥️ Interactive Web Dashboard Workstation: Streamlit workstation featuring real-time signal viewing, step-by-step digitization previews, R-peak beat segmentation, and downloadable diagnostic prediction tables.

📰 News & Updates


📌 Table of Contents


🖥️ Web Dashboard Workstation Overview

The ECGLight workstation provides a responsive user interface designed for clinical workflow exploration, research, and education. It unifies the computer vision digitization and diagnostic classification models into a seamless local web application.

Workstation Modules

  1. 📷 ECG Image Digitizer:

    • Upload scanned or photographed ECG images (.png, .jpg, .jpeg).
    • Execute the sequential YOLOv11 detection pipeline with real-time visual progress indicators.
    • Summarizes detected leads, calibrated sampling rates, and total extracted samples.
    • Automatically exports the digitized time-series CSV to output/digitization/latest_digitized.csv.
  2. 📈 ECG Signal Viewer:

    • Interactive multi-channel ECG signal visualization using native Streamlit/Vega-Lite charts with zoom, pan, and hover tooltips.
    • Supports stacked subplots (with distinct clinical lead colorings) and multi-lead overlay modes.
    • Computes statistical summaries (mean, SD, min/max, voltage range) and row-level previewing.
  3. ❤️ ECG Classification Engine:

    • Evaluates cardiac pathologies using pre-trained time-series ensemble and deep learning classifiers.
    • Automatically segments raw signals into heartbeats around R-peaks using the Pan-Tompkins algorithm.
    • Inference Mode (Unlabeled Data): Generates downloadable Predictions Tables with predicted class labels and probability confidence scores.
    • Evaluation Mode (Ground-Truth Labeled Data): Displays interactive evaluation metrics (Accuracy, $F_1$-Score, Sensitivity, Specificity, Confusion Matrix).

🔄 End-to-End Workflow

The pipeline operates in four coordinated phases: Digitization $ ightarrow$ Analysis $ ightarrow$ Segmentation $ ightarrow$ Classification. Architectural flowcharts for each phase are provided in the How It Works sections below.


🚀 Installation & Setup

Prerequisites

  • Python: 3.9+ (tested on Python 3.9 and 3.11)
  • Hardware: Standard CPU (CUDA-capable GPU optional, automatically detected)

Step-by-Step Installation

  1. Clone the Repository:

    git clone https://github.com/scai-lab/ECG-Digitization-Classification.git
    cd ECG-Digitization-Classification
  2. Create and Activate Conda Environment:

    conda env create -f environment.yml
    conda activate infer

    [!IMPORTANT] Windows Compatibility & TensorFlow Setup: If running on Windows and encountering DLL loading errors (ImportError: DLL load failed while importing _pywrap_tensorflow_internal), install the pinned TensorFlow and Protobuf pairing:

    pip install tensorflow==2.15.0 protobuf==4.25.3
  3. Download Pre-Trained Model Weights: The YOLOv11 detection checkpoints and pre-trained time-series classifiers are hosted on Polybox due to file size constraints:

    👉 Download Pre-Trained Models Directory (ETH Zürich Polybox)

    Extract the downloaded archive and place the models/ directory directly into the root of the project workspace:

    models/
    ├── digitization_models/
    │ ├── yolo11_full/weights/best.pt
    │ ├── yolo11_lead/weights/best.pt
    │ ├── yolo11_pulse/weights/best.pt
    │ └── yolo11_patch/weights/best.pt
    └── classifier_models/
    ├── mi_vs_normal_segmented/
    ├── omi_vs_nonomi/
    └── ecg_surgery/
    
  4. Launch the Web Dashboard Workstation:

    streamlit run app.py

🧠 Pre-Trained Classifiers & Tasks

The classification engine supports three distinct diagnostic tasks using the pre-trained weights in models/classifier_models/:

Diagnostic TaskModel ArchitectureExpected Input Tensor ShapeTest AccuracyTarget Positive Class
Normal vs Myocardial Infarction (MI)Arsenal Ensemble12 leads $ imes$ 140 timesteps92.3%MYOCARDIAL_INFARCTION
Occlusive MI (OMI) vs Non-OMIRocket Classifier12 leads $ imes$ 141 timesteps88.9%OMI
Pre-Procedural vs Post-Procedural MIInceptionTime Deep Net12 leads $ imes$ 140 timesteps91.4%pre-procedural MI
  • Arsenal: An ensemble of ROCKET classifiers utilizing random convolutional kernels combined with ridge regression feature classification.
  • Rocket: Random Omni-directional Kernel Extraction classifier computing high-dimensional time-series representations.
  • InceptionTime: A deep 1D convolutional neural network ensemble leveraging multi-scale temporal kernel convolutions.

🚀 Command Line Usage

Batch Signal Digitization (run_org.py)

Process structured directories of paper ECG scans in batch mode:

  1. Configure dataset directory paths in run_org.py:

    ORGANIZED_DIR="../ecg_files/ECG_organized_all"# Input dataset rootOUTPUT_DIR="../ecg_files/ECG_digitized"# Destination for CSVsCATEGORIES= ["pre", "index", "post"] # Sub-directories
  2. Run the batch digitization script:

    python run_org.py

Command-Line Model Inference (run_inference.py)

Run standalone inference on pre-digitized CSV datasets:

# 1. Normal vs MI Classification (Arsenal Model)
python archive/classification/run_inference.py --model mi_vs_normal_segmented --input data/ptb_xl/segmented_heartbeats.csv
# 2. Occlusive MI (OMI) vs Non-OMI Classification (Rocket Model)
python archive/classification/run_inference.py --model omi_vs_nonomi --input data/ecg_matrix_omi_segmented_50_150_90.csv
# 3. Custom Output Destination
python archive/classification/run_inference.py --model ecg_surgery --input data/ecg_surgery_segmented_50_150_70.csv --output results/surgery_preds.csv

📁 Repository Structure & Directory Organization

.
├── app.py # Streamlit application main router
├── config.py # Centralized configuration and model registry
├── digitization.py # Core ECGImage extraction pipeline class
├── environment.yml # Conda environment dependency specification
├── LICENSE # Non-commercial academic license agreement
├── README.md # Repository documentation
│
├── backend/ # Dashboard background execution adapters
│ ├── __init__.py # Package initializer
│ ├── digitization_runner.py # YOLO loader and single-image processor
│ └── classification_runner.py # Model loader and inference adapter
│
├── utils/ # Streamlit front-end UI view components
│ ├── __init__.py # Package initializer
│ ├── branding.py # Header titles and institutional footer logos
│ ├── css.py # Custom clinical theme and styling utilities
│ ├── hardware.py # Hardware detector (CPU/GPU)
│ ├── page_digitizer.py # ECG Digitizer page view
│ ├── page_csv_viewer.py # Interactive Signal Viewer page view
│ └── page_classifier.py # Classification workstation page view
│
├── models/ # Relocated YOLO checkpoints and classifiers (external)
│ ├── digitization_models/ # YOLOv11 weights (full, lead, pulse, patch)
│ └── classifier_models/ # Pre-trained classifier weights (Arsenal, Rocket, InceptionTime)
│
└── archive/ # Archived research, training, and CLI scripts (local)
└── classification/ # Baseline training and evaluation scripts

📷 How It Works: Signal Digitization

The core engine in digitization.py executes a multi-stage computer vision workflow to convert image pixels into calibrated voltage waveforms:

graph TD
A[ECG Image Upload] --> B[Preprocessing: Otsu & Blurring]
B --> C[YOLOv11 Detection & Segmentation]
subgraph YOLOv11 Models
C1[yolo11_full: Lead Boundaries]
C2[yolo11_lead: Text Name Labels]
C3[yolo11_pulse: Calibration Pulses]
C4[yolo11_patch: Waveform Segments]
end
C --> C1 & C2 & C3 & C4
C1 & C2 & C3 & C4 --> D[Hough Lines Calibration]
D --> E[K-Means Row & Column Grid Construction]
E --> F[Anti-Leakage Connected Components Filter]
F --> G[Centroid Trace & Resampling to 500Hz]
G --> H[Export latest_digitized.csv]
Loading
  1. Image Preprocessing: Cleans input scans using shadow removal, Otsu binarization, and Gaussian blurring to separate ink traces from paper texture.
  2. YOLO Segmentation: Applies patched YOLO segmentation models across multiple crop scales (, 4.5×, ) to bound individual lead regions.
  3. Multi-Model Object Detection: Runs YOLO detectors in parallel:
    • yolo11_full: Bounding boxes for the 12 lead channels.
    • yolo11_lead: Text label identification (I, II, aVR, V1-V6).
    • yolo11_pulse: Bounding boxes for 1 mV calibration reference pulses.
  4. Scale Calibration: Fits Hough lines to calibration pulse boundaries to compute exact voltage scaling ($ ext{V}/ ext{px}$) and time scaling ($ ext{s}/ ext{px}$).
  5. Grid Construction: Employs K-Means clustering on lead coordinates to construct regular grid layouts (3×4, 4×3, 6×2, 12×1) and resolve standard Cabrera lead ordering.
  6. Contour Tracing & Anti-Leakage Filtering: Traces pixel centroids, baseline-corrects waveforms, and applies an anti-leakage connected-component filter per crop to isolate primary waveform traces from adjacent lead leakage. Signals are resampled to 500 Hz calibrated in mV.

📈 How It Works: Signal Analysis & Visualization

graph TD
A[Upload Digitized CSV] --> B[Parse Lead Voltages & Timestamps]
B --> C[Vega-Lite Interactive Visualizer]
C --> C1[Render Stacked Leads]
C --> C2[Render Overlaid Signals]
B --> D[Compute Signal Statistics: Mean, SD, Min/Max]
D --> E[Display Summary Dataframes & Row Previews]
Loading
  1. Signal Parsing: Validates multi-lead CSV headers, timestamps, and sampling consistency.
  2. Interactive Rendering: Native Vega-Lite charts enable client-side pan, zoom, and multi-channel hover tooltips.
  3. Statistical Profiling: Calculates lead-level statistical metrics (mean, standard deviation, voltage range, min/max).

⚡ How It Works: Heartbeat Segmentation

Prepares continuous 12-lead signals for classification models via Pan-Tompkins R-peak detection:

graph TD
A[Digitized 500Hz Signal] --> B[Bandpass Filter 5-15Hz]
B --> C[Derivative Filter]
C --> D[Squaring Operation]
D --> E[Moving Window Integration]
E --> F[Adaptive Thresholding & R-Peak Search]
F --> G[Extract 140-sample Beats: 50ms pre-R, 150ms post-R]
G --> H[Max-Absolute Voltage Normalization]
Loading
  1. Bandpass Filtering: 5–15 Hz bandpass filter isolates QRS energy while suppressing muscle artifact and baseline wander.
  2. Differentiation & Squaring: Highlights steep QRS slopes and attenuates P/T waves.
  3. Moving Window Integration: Integrates energy across a 150 ms window to delineate QRS complexes.
  4. Adaptive Thresholding: Dynamically searches for R-peak maxima.
  5. Beat Windowing & Normalization: Extracts beat windows centered around R-peaks (50 ms pre-R, 150 ms post-R), normalizes max-absolute voltage, and formats output tensors (140/141 timesteps).

🧠 How It Works: Cardiac Classification

graph TD
A[Segmented Heartbeats] --> B[Numpy3D Reshaping: N_instances × 12_leads × N_timesteps]
B --> C[Select Classification Task]
subgraph Model Registry
C1[Normal vs MI: Arsenal]
C2[OMI vs non-OMI: Rocket]
C3[Pre vs Post-Procedural MI: InceptionTime]
end
C --> C1 & C2 & C3
C1 & C2 & C3 --> D[Load Pre-Trained Pickled Estimator]
D --> E[Predict Class Labels & Probabilities]
E --> F[Generate Downloadable Predictions CSV]
Loading
  1. Tensor Formatting: Formats heartbeat segments into 3D NumPy arrays (N_samples, 12_leads, N_timesteps).
  2. Model Evaluation: Invokes the pre-trained pickled estimator for the selected diagnostic endpoint.
  3. Report Generation: Formats class predictions, confidence probabilities, and diagnostic metrics for export.

🤝 Collaborating Institutions

This research project was developed in multi-center academic and clinical collaboration:

ETH ZürichIstituto Cardiocentro Ticino (EOC)USIUniversità della Campania Luigi Vanvitelli


👥 Authors & Contact

  • Shreyasvi Natrajsnatraj@ethz.ch
  • Cyrus Achtari
  • Felice Gragnano
  • Andrea Milzi
  • Marco Valgimigli
  • Diego Paez-Granados

📄 Citation

If you use ECGLight or its pre-trained models in your research, please cite our arXiv preprint:

@article{natraj2026ecglight,
title={ECGLight: Compute-Light Framework For Paper ECG Digitization and Myocardial Infarction Screening},
author={Natraj, Shreyasvi and Achtari, Cyrus and Gragnano, Felice and Milzi, Andrea and Valgimigli, Marco and Paez-Granados, Diego},
journal={arXiv preprint arXiv:2607.07683},
year={2026},
url={https://arxiv.org/abs/2607.07683},
doi={10.48550/arXiv.2607.07683}
}

APA Citation: Natraj, S., Achtari, C., Gragnano, F., Milzi, A., Valgimigli, M., & Paez-Granados, D. (2026). ECGLight: Compute-Light Framework For Paper ECG Digitization and Myocardial Infarction Screening. arXiv preprint arXiv:2607.07683. https://arxiv.org/abs/2607.07683


📄 License

This repository and model weights are released under the Non-Commercial Academic and Research License Agreement. Please refer to the LICENSE file for full terms. Free for non-profit academic and research use. Commercial use is strictly prohibited.

About

Directory containing the backend and front end of Paper ECG Digitization and Classification

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

⚡ ECGLight: Compute-Light Framework for Paper ECG Digitization & Myocardial Infarction Screening

arXivPython 3.9+PyTorchUltralytics YOLOv11Streamlit WorkstationLicense: Non-Commercial


📌 Abstract & Key Highlights

ECGLight is an end-to-end, compute-light framework and interactive web workstation for converting paper/photographed 12-lead ECG records into high-fidelity 500 Hz digitized signals and performing automated screening for Myocardial Infarction (MI) and Occlusive MI (OMI) pathologies.

💡 Designed for Low-Resource & Remote Settings: ECGLight runs completely on CPU-only hardware in <30 seconds per ECG without requiring cloud connectivity or expensive GPU infrastructure, democratizing AI-based decision support for clinics worldwide.

✨ Key Features & Capabilities

  • 📷 High-Fidelity Signal Digitization: Multi-stage computer vision pipeline combining sequential YOLOv11 object detection, scale calibration via Hough lines, K-Means grid construction, and an anti-leakage connected-component filter to extract clean 500 Hz 12-lead signals from smartphone photos or scans.
  • ❤️ High-Accuracy MI & OMI Screening:
    • 95.51% Accuracy ($F_1 = 0.9519$) for MI detection on the benchmark PTB-XL dataset (21,799 ECGs).
    • 88.89% Accuracy ($F_1 = 0.8862$) for Occlusive MI (OMI) screening on the hospital-acquired ECG-Matrix dataset.
  • ⚡ On-Device & Resource-Efficient: Fully functional on standard consumer laptop CPUs or CUDA GPUs.
  • 🖥️ Interactive Web Dashboard Workstation: Streamlit workstation featuring real-time signal viewing, step-by-step digitization previews, R-peak beat segmentation, and downloadable diagnostic prediction tables.

📰 News & Updates


📌 Table of Contents


🖥️ Web Dashboard Workstation Overview

The ECGLight workstation provides a responsive user interface designed for clinical workflow exploration, research, and education. It unifies the computer vision digitization and diagnostic classification models into a seamless local web application.

Workstation Modules

  1. 📷 ECG Image Digitizer:

    • Upload scanned or photographed ECG images (.png, .jpg, .jpeg).
    • Execute the sequential YOLOv11 detection pipeline with real-time visual progress indicators.
    • Summarizes detected leads, calibrated sampling rates, and total extracted samples.
    • Automatically exports the digitized time-series CSV to output/digitization/latest_digitized.csv.
  2. 📈 ECG Signal Viewer:

    • Interactive multi-channel ECG signal visualization using native Streamlit/Vega-Lite charts with zoom, pan, and hover tooltips.
    • Supports stacked subplots (with distinct clinical lead colorings) and multi-lead overlay modes.
    • Computes statistical summaries (mean, SD, min/max, voltage range) and row-level previewing.
  3. ❤️ ECG Classification Engine:

    • Evaluates cardiac pathologies using pre-trained time-series ensemble and deep learning classifiers.
    • Automatically segments raw signals into heartbeats around R-peaks using the Pan-Tompkins algorithm.
    • Inference Mode (Unlabeled Data): Generates downloadable Predictions Tables with predicted class labels and probability confidence scores.
    • Evaluation Mode (Ground-Truth Labeled Data): Displays interactive evaluation metrics (Accuracy, $F_1$-Score, Sensitivity, Specificity, Confusion Matrix).

🔄 End-to-End Workflow

The pipeline operates in four coordinated phases: Digitization $ ightarrow$ Analysis $ ightarrow$ Segmentation $ ightarrow$ Classification. Architectural flowcharts for each phase are provided in the How It Works sections below.


🚀 Installation & Setup

Prerequisites

  • Python: 3.9+ (tested on Python 3.9 and 3.11)
  • Hardware: Standard CPU (CUDA-capable GPU optional, automatically detected)

Step-by-Step Installation

  1. Clone the Repository:

    git clone https://github.com/scai-lab/ECG-Digitization-Classification.git
    cd ECG-Digitization-Classification
  2. Create and Activate Conda Environment:

    conda env create -f environment.yml
    conda activate infer

    [!IMPORTANT] Windows Compatibility & TensorFlow Setup: If running on Windows and encountering DLL loading errors (ImportError: DLL load failed while importing _pywrap_tensorflow_internal), install the pinned TensorFlow and Protobuf pairing:

    pip install tensorflow==2.15.0 protobuf==4.25.3
  3. Download Pre-Trained Model Weights: The YOLOv11 detection checkpoints and pre-trained time-series classifiers are hosted on Polybox due to file size constraints:

    👉 Download Pre-Trained Models Directory (ETH Zürich Polybox)

    Extract the downloaded archive and place the models/ directory directly into the root of the project workspace:

    models/
    ├── digitization_models/
    │ ├── yolo11_full/weights/best.pt
    │ ├── yolo11_lead/weights/best.pt
    │ ├── yolo11_pulse/weights/best.pt
    │ └── yolo11_patch/weights/best.pt
    └── classifier_models/
    ├── mi_vs_normal_segmented/
    ├── omi_vs_nonomi/
    └── ecg_surgery/
    
  4. Launch the Web Dashboard Workstation:

    streamlit run app.py

🧠 Pre-Trained Classifiers & Tasks

The classification engine supports three distinct diagnostic tasks using the pre-trained weights in models/classifier_models/:

Diagnostic TaskModel ArchitectureExpected Input Tensor ShapeTest AccuracyTarget Positive Class
Normal vs Myocardial Infarction (MI)Arsenal Ensemble12 leads $ imes$ 140 timesteps92.3%MYOCARDIAL_INFARCTION
Occlusive MI (OMI) vs Non-OMIRocket Classifier12 leads $ imes$ 141 timesteps88.9%OMI
Pre-Procedural vs Post-Procedural MIInceptionTime Deep Net12 leads $ imes$ 140 timesteps91.4%pre-procedural MI
  • Arsenal: An ensemble of ROCKET classifiers utilizing random convolutional kernels combined with ridge regression feature classification.
  • Rocket: Random Omni-directional Kernel Extraction classifier computing high-dimensional time-series representations.
  • InceptionTime: A deep 1D convolutional neural network ensemble leveraging multi-scale temporal kernel convolutions.

🚀 Command Line Usage

Batch Signal Digitization (run_org.py)

Process structured directories of paper ECG scans in batch mode:

  1. Configure dataset directory paths in run_org.py:

    ORGANIZED_DIR="../ecg_files/ECG_organized_all"# Input dataset rootOUTPUT_DIR="../ecg_files/ECG_digitized"# Destination for CSVsCATEGORIES= ["pre", "index", "post"] # Sub-directories
  2. Run the batch digitization script:

    python run_org.py

Command-Line Model Inference (run_inference.py)

Run standalone inference on pre-digitized CSV datasets:

# 1. Normal vs MI Classification (Arsenal Model)
python archive/classification/run_inference.py --model mi_vs_normal_segmented --input data/ptb_xl/segmented_heartbeats.csv
# 2. Occlusive MI (OMI) vs Non-OMI Classification (Rocket Model)
python archive/classification/run_inference.py --model omi_vs_nonomi --input data/ecg_matrix_omi_segmented_50_150_90.csv
# 3. Custom Output Destination
python archive/classification/run_inference.py --model ecg_surgery --input data/ecg_surgery_segmented_50_150_70.csv --output results/surgery_preds.csv

📁 Repository Structure & Directory Organization

.
├── app.py # Streamlit application main router
├── config.py # Centralized configuration and model registry
├── digitization.py # Core ECGImage extraction pipeline class
├── environment.yml # Conda environment dependency specification
├── LICENSE # Non-commercial academic license agreement
├── README.md # Repository documentation
│
├── backend/ # Dashboard background execution adapters
│ ├── __init__.py # Package initializer
│ ├── digitization_runner.py # YOLO loader and single-image processor
│ └── classification_runner.py # Model loader and inference adapter
│
├── utils/ # Streamlit front-end UI view components
│ ├── __init__.py # Package initializer
│ ├── branding.py # Header titles and institutional footer logos
│ ├── css.py # Custom clinical theme and styling utilities
│ ├── hardware.py # Hardware detector (CPU/GPU)
│ ├── page_digitizer.py # ECG Digitizer page view
│ ├── page_csv_viewer.py # Interactive Signal Viewer page view
│ └── page_classifier.py # Classification workstation page view
│
├── models/ # Relocated YOLO checkpoints and classifiers (external)
│ ├── digitization_models/ # YOLOv11 weights (full, lead, pulse, patch)
│ └── classifier_models/ # Pre-trained classifier weights (Arsenal, Rocket, InceptionTime)
│
└── archive/ # Archived research, training, and CLI scripts (local)
└── classification/ # Baseline training and evaluation scripts

📷 How It Works: Signal Digitization

The core engine in digitization.py executes a multi-stage computer vision workflow to convert image pixels into calibrated voltage waveforms:

graph TD
A[ECG Image Upload] --> B[Preprocessing: Otsu & Blurring]
B --> C[YOLOv11 Detection & Segmentation]
subgraph YOLOv11 Models
C1[yolo11_full: Lead Boundaries]
C2[yolo11_lead: Text Name Labels]
C3[yolo11_pulse: Calibration Pulses]
C4[yolo11_patch: Waveform Segments]
end
C --> C1 & C2 & C3 & C4
C1 & C2 & C3 & C4 --> D[Hough Lines Calibration]
D --> E[K-Means Row & Column Grid Construction]
E --> F[Anti-Leakage Connected Components Filter]
F --> G[Centroid Trace & Resampling to 500Hz]
G --> H[Export latest_digitized.csv]
Loading
  1. Image Preprocessing: Cleans input scans using shadow removal, Otsu binarization, and Gaussian blurring to separate ink traces from paper texture.
  2. YOLO Segmentation: Applies patched YOLO segmentation models across multiple crop scales (, 4.5×, ) to bound individual lead regions.
  3. Multi-Model Object Detection: Runs YOLO detectors in parallel:
    • yolo11_full: Bounding boxes for the 12 lead channels.
    • yolo11_lead: Text label identification (I, II, aVR, V1-V6).
    • yolo11_pulse: Bounding boxes for 1 mV calibration reference pulses.
  4. Scale Calibration: Fits Hough lines to calibration pulse boundaries to compute exact voltage scaling ($ ext{V}/ ext{px}$) and time scaling ($ ext{s}/ ext{px}$).
  5. Grid Construction: Employs K-Means clustering on lead coordinates to construct regular grid layouts (3×4, 4×3, 6×2, 12×1) and resolve standard Cabrera lead ordering.
  6. Contour Tracing & Anti-Leakage Filtering: Traces pixel centroids, baseline-corrects waveforms, and applies an anti-leakage connected-component filter per crop to isolate primary waveform traces from adjacent lead leakage. Signals are resampled to 500 Hz calibrated in mV.

📈 How It Works: Signal Analysis & Visualization

graph TD
A[Upload Digitized CSV] --> B[Parse Lead Voltages & Timestamps]
B --> C[Vega-Lite Interactive Visualizer]
C --> C1[Render Stacked Leads]
C --> C2[Render Overlaid Signals]
B --> D[Compute Signal Statistics: Mean, SD, Min/Max]
D --> E[Display Summary Dataframes & Row Previews]
Loading
  1. Signal Parsing: Validates multi-lead CSV headers, timestamps, and sampling consistency.
  2. Interactive Rendering: Native Vega-Lite charts enable client-side pan, zoom, and multi-channel hover tooltips.
  3. Statistical Profiling: Calculates lead-level statistical metrics (mean, standard deviation, voltage range, min/max).

⚡ How It Works: Heartbeat Segmentation

Prepares continuous 12-lead signals for classification models via Pan-Tompkins R-peak detection:

graph TD
A[Digitized 500Hz Signal] --> B[Bandpass Filter 5-15Hz]
B --> C[Derivative Filter]
C --> D[Squaring Operation]
D --> E[Moving Window Integration]
E --> F[Adaptive Thresholding & R-Peak Search]
F --> G[Extract 140-sample Beats: 50ms pre-R, 150ms post-R]
G --> H[Max-Absolute Voltage Normalization]
Loading
  1. Bandpass Filtering: 5–15 Hz bandpass filter isolates QRS energy while suppressing muscle artifact and baseline wander.
  2. Differentiation & Squaring: Highlights steep QRS slopes and attenuates P/T waves.
  3. Moving Window Integration: Integrates energy across a 150 ms window to delineate QRS complexes.
  4. Adaptive Thresholding: Dynamically searches for R-peak maxima.
  5. Beat Windowing & Normalization: Extracts beat windows centered around R-peaks (50 ms pre-R, 150 ms post-R), normalizes max-absolute voltage, and formats output tensors (140/141 timesteps).

🧠 How It Works: Cardiac Classification

graph TD
A[Segmented Heartbeats] --> B[Numpy3D Reshaping: N_instances × 12_leads × N_timesteps]
B --> C[Select Classification Task]
subgraph Model Registry
C1[Normal vs MI: Arsenal]
C2[OMI vs non-OMI: Rocket]
C3[Pre vs Post-Procedural MI: InceptionTime]
end
C --> C1 & C2 & C3
C1 & C2 & C3 --> D[Load Pre-Trained Pickled Estimator]
D --> E[Predict Class Labels & Probabilities]
E --> F[Generate Downloadable Predictions CSV]
Loading
  1. Tensor Formatting: Formats heartbeat segments into 3D NumPy arrays (N_samples, 12_leads, N_timesteps).
  2. Model Evaluation: Invokes the pre-trained pickled estimator for the selected diagnostic endpoint.
  3. Report Generation: Formats class predictions, confidence probabilities, and diagnostic metrics for export.

🤝 Collaborating Institutions

This research project was developed in multi-center academic and clinical collaboration:

ETH ZürichIstituto Cardiocentro Ticino (EOC)USIUniversità della Campania Luigi Vanvitelli


👥 Authors & Contact

  • Shreyasvi Natrajsnatraj@ethz.ch
  • Cyrus Achtari
  • Felice Gragnano
  • Andrea Milzi
  • Marco Valgimigli
  • Diego Paez-Granados

📄 Citation

If you use ECGLight or its pre-trained models in your research, please cite our arXiv preprint:

@article{natraj2026ecglight,
title={ECGLight: Compute-Light Framework For Paper ECG Digitization and Myocardial Infarction Screening},
author={Natraj, Shreyasvi and Achtari, Cyrus and Gragnano, Felice and Milzi, Andrea and Valgimigli, Marco and Paez-Granados, Diego},
journal={arXiv preprint arXiv:2607.07683},
year={2026},
url={https://arxiv.org/abs/2607.07683},
doi={10.48550/arXiv.2607.07683}
}

APA Citation: Natraj, S., Achtari, C., Gragnano, F., Milzi, A., Valgimigli, M., & Paez-Granados, D. (2026). ECGLight: Compute-Light Framework For Paper ECG Digitization and Myocardial Infarction Screening. arXiv preprint arXiv:2607.07683. https://arxiv.org/abs/2607.07683


📄 License

This repository and model weights are released under the Non-Commercial Academic and Research License Agreement. Please refer to the LICENSE file for full terms. Free for non-profit academic and research use. Commercial use is strictly prohibited.

About

Directory containing the backend and front end of Paper ECG Digitization and Classification

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

⚡ ECGLight: Compute-Light Framework for Paper ECG Digitization & Myocardial Infarction Screening

arXivPython 3.9+PyTorchUltralytics YOLOv11Streamlit WorkstationLicense: Non-Commercial


📌 Abstract & Key Highlights

ECGLight is an end-to-end, compute-light framework and interactive web workstation for converting paper/photographed 12-lead ECG records into high-fidelity 500 Hz digitized signals and performing automated screening for Myocardial Infarction (MI) and Occlusive MI (OMI) pathologies.

💡 Designed for Low-Resource & Remote Settings: ECGLight runs completely on CPU-only hardware in <30 seconds per ECG without requiring cloud connectivity or expensive GPU infrastructure, democratizing AI-based decision support for clinics worldwide.

✨ Key Features & Capabilities

  • 📷 High-Fidelity Signal Digitization: Multi-stage computer vision pipeline combining sequential YOLOv11 object detection, scale calibration via Hough lines, K-Means grid construction, and an anti-leakage connected-component filter to extract clean 500 Hz 12-lead signals from smartphone photos or scans.
  • ❤️ High-Accuracy MI & OMI Screening:
    • 95.51% Accuracy ($F_1 = 0.9519$) for MI detection on the benchmark PTB-XL dataset (21,799 ECGs).
    • 88.89% Accuracy ($F_1 = 0.8862$) for Occlusive MI (OMI) screening on the hospital-acquired ECG-Matrix dataset.
  • ⚡ On-Device & Resource-Efficient: Fully functional on standard consumer laptop CPUs or CUDA GPUs.
  • 🖥️ Interactive Web Dashboard Workstation: Streamlit workstation featuring real-time signal viewing, step-by-step digitization previews, R-peak beat segmentation, and downloadable diagnostic prediction tables.

📰 News & Updates


📌 Table of Contents


🖥️ Web Dashboard Workstation Overview

The ECGLight workstation provides a responsive user interface designed for clinical workflow exploration, research, and education. It unifies the computer vision digitization and diagnostic classification models into a seamless local web application.

Workstation Modules

  1. 📷 ECG Image Digitizer:

    • Upload scanned or photographed ECG images (.png, .jpg, .jpeg).
    • Execute the sequential YOLOv11 detection pipeline with real-time visual progress indicators.
    • Summarizes detected leads, calibrated sampling rates, and total extracted samples.
    • Automatically exports the digitized time-series CSV to output/digitization/latest_digitized.csv.
  2. 📈 ECG Signal Viewer:

    • Interactive multi-channel ECG signal visualization using native Streamlit/Vega-Lite charts with zoom, pan, and hover tooltips.
    • Supports stacked subplots (with distinct clinical lead colorings) and multi-lead overlay modes.
    • Computes statistical summaries (mean, SD, min/max, voltage range) and row-level previewing.
  3. ❤️ ECG Classification Engine:

    • Evaluates cardiac pathologies using pre-trained time-series ensemble and deep learning classifiers.
    • Automatically segments raw signals into heartbeats around R-peaks using the Pan-Tompkins algorithm.
    • Inference Mode (Unlabeled Data): Generates downloadable Predictions Tables with predicted class labels and probability confidence scores.
    • Evaluation Mode (Ground-Truth Labeled Data): Displays interactive evaluation metrics (Accuracy, $F_1$-Score, Sensitivity, Specificity, Confusion Matrix).

🔄 End-to-End Workflow

The pipeline operates in four coordinated phases: Digitization $ ightarrow$ Analysis $ ightarrow$ Segmentation $ ightarrow$ Classification. Architectural flowcharts for each phase are provided in the How It Works sections below.


🚀 Installation & Setup

Prerequisites

  • Python: 3.9+ (tested on Python 3.9 and 3.11)
  • Hardware: Standard CPU (CUDA-capable GPU optional, automatically detected)

Step-by-Step Installation

  1. Clone the Repository:

    git clone https://github.com/scai-lab/ECG-Digitization-Classification.git
    cd ECG-Digitization-Classification
  2. Create and Activate Conda Environment:

    conda env create -f environment.yml
    conda activate infer

    [!IMPORTANT] Windows Compatibility & TensorFlow Setup: If running on Windows and encountering DLL loading errors (ImportError: DLL load failed while importing _pywrap_tensorflow_internal), install the pinned TensorFlow and Protobuf pairing:

    pip install tensorflow==2.15.0 protobuf==4.25.3
  3. Download Pre-Trained Model Weights: The YOLOv11 detection checkpoints and pre-trained time-series classifiers are hosted on Polybox due to file size constraints:

    👉 Download Pre-Trained Models Directory (ETH Zürich Polybox)

    Extract the downloaded archive and place the models/ directory directly into the root of the project workspace:

    models/
    ├── digitization_models/
    │ ├── yolo11_full/weights/best.pt
    │ ├── yolo11_lead/weights/best.pt
    │ ├── yolo11_pulse/weights/best.pt
    │ └── yolo11_patch/weights/best.pt
    └── classifier_models/
    ├── mi_vs_normal_segmented/
    ├── omi_vs_nonomi/
    └── ecg_surgery/
    
  4. Launch the Web Dashboard Workstation:

    streamlit run app.py

🧠 Pre-Trained Classifiers & Tasks

The classification engine supports three distinct diagnostic tasks using the pre-trained weights in models/classifier_models/:

Diagnostic TaskModel ArchitectureExpected Input Tensor ShapeTest AccuracyTarget Positive Class
Normal vs Myocardial Infarction (MI)Arsenal Ensemble12 leads $ imes$ 140 timesteps92.3%MYOCARDIAL_INFARCTION
Occlusive MI (OMI) vs Non-OMIRocket Classifier12 leads $ imes$ 141 timesteps88.9%OMI
Pre-Procedural vs Post-Procedural MIInceptionTime Deep Net12 leads $ imes$ 140 timesteps91.4%pre-procedural MI
  • Arsenal: An ensemble of ROCKET classifiers utilizing random convolutional kernels combined with ridge regression feature classification.
  • Rocket: Random Omni-directional Kernel Extraction classifier computing high-dimensional time-series representations.
  • InceptionTime: A deep 1D convolutional neural network ensemble leveraging multi-scale temporal kernel convolutions.

🚀 Command Line Usage

Batch Signal Digitization (run_org.py)

Process structured directories of paper ECG scans in batch mode:

  1. Configure dataset directory paths in run_org.py:

    ORGANIZED_DIR="../ecg_files/ECG_organized_all"# Input dataset rootOUTPUT_DIR="../ecg_files/ECG_digitized"# Destination for CSVsCATEGORIES= ["pre", "index", "post"] # Sub-directories
  2. Run the batch digitization script:

    python run_org.py

Command-Line Model Inference (run_inference.py)

Run standalone inference on pre-digitized CSV datasets:

# 1. Normal vs MI Classification (Arsenal Model)
python archive/classification/run_inference.py --model mi_vs_normal_segmented --input data/ptb_xl/segmented_heartbeats.csv
# 2. Occlusive MI (OMI) vs Non-OMI Classification (Rocket Model)
python archive/classification/run_inference.py --model omi_vs_nonomi --input data/ecg_matrix_omi_segmented_50_150_90.csv
# 3. Custom Output Destination
python archive/classification/run_inference.py --model ecg_surgery --input data/ecg_surgery_segmented_50_150_70.csv --output results/surgery_preds.csv

📁 Repository Structure & Directory Organization

.
├── app.py # Streamlit application main router
├── config.py # Centralized configuration and model registry
├── digitization.py # Core ECGImage extraction pipeline class
├── environment.yml # Conda environment dependency specification
├── LICENSE # Non-commercial academic license agreement
├── README.md # Repository documentation
│
├── backend/ # Dashboard background execution adapters
│ ├── __init__.py # Package initializer
│ ├── digitization_runner.py # YOLO loader and single-image processor
│ └── classification_runner.py # Model loader and inference adapter
│
├── utils/ # Streamlit front-end UI view components
│ ├── __init__.py # Package initializer
│ ├── branding.py # Header titles and institutional footer logos
│ ├── css.py # Custom clinical theme and styling utilities
│ ├── hardware.py # Hardware detector (CPU/GPU)
│ ├── page_digitizer.py # ECG Digitizer page view
│ ├── page_csv_viewer.py # Interactive Signal Viewer page view
│ └── page_classifier.py # Classification workstation page view
│
├── models/ # Relocated YOLO checkpoints and classifiers (external)
│ ├── digitization_models/ # YOLOv11 weights (full, lead, pulse, patch)
│ └── classifier_models/ # Pre-trained classifier weights (Arsenal, Rocket, InceptionTime)
│
└── archive/ # Archived research, training, and CLI scripts (local)
└── classification/ # Baseline training and evaluation scripts

📷 How It Works: Signal Digitization

The core engine in digitization.py executes a multi-stage computer vision workflow to convert image pixels into calibrated voltage waveforms:

graph TD
A[ECG Image Upload] --> B[Preprocessing: Otsu & Blurring]
B --> C[YOLOv11 Detection & Segmentation]
subgraph YOLOv11 Models
C1[yolo11_full: Lead Boundaries]
C2[yolo11_lead: Text Name Labels]
C3[yolo11_pulse: Calibration Pulses]
C4[yolo11_patch: Waveform Segments]
end
C --> C1 & C2 & C3 & C4
C1 & C2 & C3 & C4 --> D[Hough Lines Calibration]
D --> E[K-Means Row & Column Grid Construction]
E --> F[Anti-Leakage Connected Components Filter]
F --> G[Centroid Trace & Resampling to 500Hz]
G --> H[Export latest_digitized.csv]
Loading
  1. Image Preprocessing: Cleans input scans using shadow removal, Otsu binarization, and Gaussian blurring to separate ink traces from paper texture.
  2. YOLO Segmentation: Applies patched YOLO segmentation models across multiple crop scales (, 4.5×, ) to bound individual lead regions.
  3. Multi-Model Object Detection: Runs YOLO detectors in parallel:
    • yolo11_full: Bounding boxes for the 12 lead channels.
    • yolo11_lead: Text label identification (I, II, aVR, V1-V6).
    • yolo11_pulse: Bounding boxes for 1 mV calibration reference pulses.
  4. Scale Calibration: Fits Hough lines to calibration pulse boundaries to compute exact voltage scaling ($ ext{V}/ ext{px}$) and time scaling ($ ext{s}/ ext{px}$).
  5. Grid Construction: Employs K-Means clustering on lead coordinates to construct regular grid layouts (3×4, 4×3, 6×2, 12×1) and resolve standard Cabrera lead ordering.
  6. Contour Tracing & Anti-Leakage Filtering: Traces pixel centroids, baseline-corrects waveforms, and applies an anti-leakage connected-component filter per crop to isolate primary waveform traces from adjacent lead leakage. Signals are resampled to 500 Hz calibrated in mV.

📈 How It Works: Signal Analysis & Visualization

graph TD
A[Upload Digitized CSV] --> B[Parse Lead Voltages & Timestamps]
B --> C[Vega-Lite Interactive Visualizer]
C --> C1[Render Stacked Leads]
C --> C2[Render Overlaid Signals]
B --> D[Compute Signal Statistics: Mean, SD, Min/Max]
D --> E[Display Summary Dataframes & Row Previews]
Loading
  1. Signal Parsing: Validates multi-lead CSV headers, timestamps, and sampling consistency.
  2. Interactive Rendering: Native Vega-Lite charts enable client-side pan, zoom, and multi-channel hover tooltips.
  3. Statistical Profiling: Calculates lead-level statistical metrics (mean, standard deviation, voltage range, min/max).

⚡ How It Works: Heartbeat Segmentation

Prepares continuous 12-lead signals for classification models via Pan-Tompkins R-peak detection:

graph TD
A[Digitized 500Hz Signal] --> B[Bandpass Filter 5-15Hz]
B --> C[Derivative Filter]
C --> D[Squaring Operation]
D --> E[Moving Window Integration]
E --> F[Adaptive Thresholding & R-Peak Search]
F --> G[Extract 140-sample Beats: 50ms pre-R, 150ms post-R]
G --> H[Max-Absolute Voltage Normalization]
Loading
  1. Bandpass Filtering: 5–15 Hz bandpass filter isolates QRS energy while suppressing muscle artifact and baseline wander.
  2. Differentiation & Squaring: Highlights steep QRS slopes and attenuates P/T waves.
  3. Moving Window Integration: Integrates energy across a 150 ms window to delineate QRS complexes.
  4. Adaptive Thresholding: Dynamically searches for R-peak maxima.
  5. Beat Windowing & Normalization: Extracts beat windows centered around R-peaks (50 ms pre-R, 150 ms post-R), normalizes max-absolute voltage, and formats output tensors (140/141 timesteps).

🧠 How It Works: Cardiac Classification

graph TD
A[Segmented Heartbeats] --> B[Numpy3D Reshaping: N_instances × 12_leads × N_timesteps]
B --> C[Select Classification Task]
subgraph Model Registry
C1[Normal vs MI: Arsenal]
C2[OMI vs non-OMI: Rocket]
C3[Pre vs Post-Procedural MI: InceptionTime]
end
C --> C1 & C2 & C3
C1 & C2 & C3 --> D[Load Pre-Trained Pickled Estimator]
D --> E[Predict Class Labels & Probabilities]
E --> F[Generate Downloadable Predictions CSV]
Loading
  1. Tensor Formatting: Formats heartbeat segments into 3D NumPy arrays (N_samples, 12_leads, N_timesteps).
  2. Model Evaluation: Invokes the pre-trained pickled estimator for the selected diagnostic endpoint.
  3. Report Generation: Formats class predictions, confidence probabilities, and diagnostic metrics for export.

🤝 Collaborating Institutions

This research project was developed in multi-center academic and clinical collaboration:

ETH ZürichIstituto Cardiocentro Ticino (EOC)USIUniversità della Campania Luigi Vanvitelli


👥 Authors & Contact

  • Shreyasvi Natrajsnatraj@ethz.ch
  • Cyrus Achtari
  • Felice Gragnano
  • Andrea Milzi
  • Marco Valgimigli
  • Diego Paez-Granados

📄 Citation

If you use ECGLight or its pre-trained models in your research, please cite our arXiv preprint:

@article{natraj2026ecglight,
title={ECGLight: Compute-Light Framework For Paper ECG Digitization and Myocardial Infarction Screening},
author={Natraj, Shreyasvi and Achtari, Cyrus and Gragnano, Felice and Milzi, Andrea and Valgimigli, Marco and Paez-Granados, Diego},
journal={arXiv preprint arXiv:2607.07683},
year={2026},
url={https://arxiv.org/abs/2607.07683},
doi={10.48550/arXiv.2607.07683}
}

APA Citation: Natraj, S., Achtari, C., Gragnano, F., Milzi, A., Valgimigli, M., & Paez-Granados, D. (2026). ECGLight: Compute-Light Framework For Paper ECG Digitization and Myocardial Infarction Screening. arXiv preprint arXiv:2607.07683. https://arxiv.org/abs/2607.07683


📄 License

This repository and model weights are released under the Non-Commercial Academic and Research License Agreement. Please refer to the LICENSE file for full terms. Free for non-profit academic and research use. Commercial use is strictly prohibited.

About

Directory containing the backend and front end of Paper ECG Digitization and Classification

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages