1. MEHRAN UNIVERSITY OF ENGINEERING AND
TECHNOLOGY JAMSHORO
SUBJECT : NEUROSCIENCES AND NEURAL NETWORKS
PROJECT TITLE : ECG Signal Processingin MATLAB -
Detecting R-Peaks.
2. SUBMITTED TO : DANIYAL MAHESHWARI
SUBMITTED BY : SHANZA KAIMKHANI
INTRODUCTION
ELECTROCARDIOGRAM(ECG)
□ An electrocardiogram(ECG) is a test which measures the electrical
activity of your heart to show whether or not it is working normally.
□ An ECG records the heart’s rhythm and activity on a moving strip of
paper or a line on a screen. Your doctor can read and interpret the peaks
and dips on paper or screen to see if there is any abnormalor unusual
activity.
What can an ECG (electrocardiogram) show?
3. □ An electrocardiogramcan be a usefulway to find out whether your
high blood pressurehas caused any damage to your heart or blood
vessels. Becauseof this, you may be asked to have an ECG when you are
firstdiagnosed with high blood pressure.
Some of the things an ECG reading can detect are:
□ cholesterolclogging up your heart’s blood supply
□ a heart attack in the past
□ enlargement of one side of the heart
□ abnormalheart rhythms
How is an ECG carried out?
□ An ECG (electrocardiogram) is a safe and painless test which normally
only takes a few minutes.
□ Leads froman electrocardiograph machine are attached to the skin on
your arms, legs and chest using sticky patches. These leads read signals
fromyour heart and send this information to the electrocardiograph.
The machine then prints the reading on a paper strip or on a screen.
BASIC TASK
The basic task of electrocardiogram (ECG) processing is R-peaks detection.
There are some difficulties one can encounter in processing ECG: irregular
distance between peaks, irregular peak form, presenceof low-frequency
component in ECG due to patient breathing etc. To solvethe task the
processing pipeline should contain particular stages to reduce influence of
those factors. Presentsampledemonstrates such a pipeline. The aim is to
show results of processing in main pipeline stages.
4. □ An Ideal ECG Looks LikeThis And ItKeeps Repeating Itself.
□ We Will Try To Detect The R-Peaks In This Project.
R-PEAKS DETECTION IN MATLAB
□ A General Noise Corrupted ECG signal Looks Like This
□ The ECG Sinal We Are Going To Work With Looks Like This
□ A Closer Look At The Signal
5. STEPS FOR DETECTION
1 Remove Low Frequency Components
1 Change to frequencydomainusingfft
2 Remove lowfrequencycomponents
3 Back to time domainusingfft
2 find local maxima using widowed filter
3 Remove Small values,storesignificantones
4 Adjustfilter sizeand repeat 2,3
HOW IT WORKS ?
(Fig 1)
Let us have some digital ECG signal — that is our input data
6. (Fig 2)
As one can see the ECG is uneven. Thus our first step is to straighten it. To say that in
mathematical language, we should remove low-frequency component. The idea is to
apply direct fast Fourier transform — FFT, remove low frequencies and restore ECG
with the help of inverse FFT. Here is the result of FFT processing
(Fig 3)
Our second step is to find local maxima. To do that we use windowed filter that
“sees” only maximum in his window and ignores all other values. On this step we use
window of default size. As result we get this
(fig 4)
7. Now we should remove small valuesand preserve significant ones — fig. 4. Here we are
using a threshold filter.
(Fig 5)
In this case the result is good but in general case we cannot be sure we have all the
peaks. So the next step is to adjust filter window size and repeat filtering — fig. 5.
Compare the result with fig. 3 — now filtering quality is much better.
(Fig 6)
Now we are ready to get the final result and here it is
8. FINAL RESULT OF ALGORITHM
MATLAB DEMONSTRATION
The demo package includes 5 files — two MatLab scripts, two data samples and
description:
ecgdemo.m — main MatLab script,
ecgdemowinmax.m —window peak filter script,
ecgdemodata1.mat — first sample ECG data file,
ecgdemodata2.mat — secondsample ECG data file,
readme.txt — description.
Some technicalnotes on demo:
To run the sample MatLab should be installed on your computer.
Unpack the sample and copy .m and .mat files into MatLab work directory.
Start up MatLab and type in:
>>ecgdemo
□ After openMATLABYouHave To Go To The Directory Where YouHave
Downloaded The Code.
□ Or Paste The Code In Script File.
9. % ECGDEMO ECG PROCESSING DEMONSTRATION - R-PEAKS DETECTION
%
% This file is a part of a package that contains 5 files:
%
% 1. ecgdemo.m - (this file) main script file;
% 2. ecgdemowinmax.m - window filter script file;
% 3. ecgdemodata1.mat - first ecg data sample;
% 4. ecgdemodata2.mat - second ecg data sample;
% 5. readme.txt - description.
%
% The package downloaded from http://www.librow.com
% To contact the author of the sample write to Sergey Chernenko:
% S.Chernenko@librow.com
%
% To run the demo put
%
% ecgdemo.m;
% ecgdemowinmax.m;
% ecgdemodata1.mat;
% ecgdemodata2.mat
%
% in MatLab's "work" directory, run MatLab and type in
%
% >> ecgdemo
%
% The code is property of LIBROW
% You can use it on your own
% When utilizing credit LIBROW site
10. % We are processing two data samples to demonstrate two different
situations
for demo = 1:2:3
% Clear our variables
clear ecg samplingrate corrected filtered1 peaks1 filtered2 peaks2
fresult
% Load data sample
switch(demo)
case 1,
plotname = 'Sample 1';
load ecgdemodata1;
case 3,
plotname = 'Sample 2';
load ecgdemodata2;
end
% Remove lower frequencies
fresult=fft(ecg);
fresult(1 : round(length(fresult)*5/samplingrate))=0;
fresult(end - round(length(fresult)*5/samplingrate) : end)=0;
corrected=real(ifft(fresult));
% Filter - first pass
WinSize = floor(samplingrate * 571 / 1000);
if rem(WinSize,2)==0
WinSize = WinSize+1;
end
filtered1=ecgdemowinmax(corrected, WinSize);
% Scale ecg
peaks1=filtered1/(max(filtered1)/7);
% Filter by threshold filter
for data = 1:1:length(peaks1)
if peaks1(data) < 4
peaks1(data) = 0;
else
peaks1(data)=1;
end
11. end
positions=find(peaks1);
distance=positions(2)-positions(1);
for data=1:1:length(positions)-1
if positions(data+1)-positions(data)<distance
distance=positions(data+1)-positions(data);
end
end
% Optimize filter window size
QRdistance=floor(0.04*samplingrate);
if rem(QRdistance,2)==0
QRdistance=QRdistance+1;
end
WinSize=2*distance-QRdistance;
% Filter - second pass
filtered2=ecgdemowinmax(corrected, WinSize);
peaks2=filtered2;
for data=1:1:length(peaks2)
if peaks2(data)<4
peaks2(data)=0;
else
peaks2(data)=1;
end
end
% Create figure - stages of processing
figure(demo); set(demo, 'Name', strcat(plotname, ' - Processing
Stages'));
% Original input ECG data
subplot(3, 2, 1); plot((ecg-min(ecg))/(max(ecg)-min(ecg)));
title('bf1. Original ECG'); ylim([-0.2 1.2]);
% ECG with removed low-frequency component
subplot(3, 2, 2);
plot((corrected-min(corrected))/(max(corrected)-min(corrected)));
title('bf2. FFT Filtered ECG'); ylim([-0.2 1.2]);
% Filtered ECG (1-st pass) - filter has default window size
12. subplot(3, 2, 3);
stem((filtered1-min(filtered1))/(max(filtered1)-min(filtered1)));
title('bf3. Filtered ECG - 1^{st} Pass'); ylim([0 1.4]);
% Detected peaks in filtered ECG
subplot(3, 2, 4); stem(peaks1);
title('bf4. Detected Peaks'); ylim([0 1.4]);
% Filtered ECG (2-d pass) - now filter has optimized window size
subplot(3, 2, 5);
stem((filtered2-min(filtered2))/(max(filtered2)-min(filtered2)));
title('bf5. Filtered ECG - 2^d Pass'); ylim([0 1.4]);
% Detected peaks - final result
subplot(3, 2, 6); stem(peaks2);
title('bf6. Detected Peaks - Finally'); ylim([0 1.4]);
% Create figure - result
figure(demo+1); set(demo+1, 'Name', strcat(plotname, ' - Result'));
% Plotting ECG in green
plot((ecg-min(ecg))/(max(ecg)-min(ecg)), '-g'); title('bf
Comparative ECG R-Peak Detection Plot');
% Show peaks in the same picture
hold on
% Stemming peaks in dashed black
stem(peaks2'.*((ecg-min(ecg))/(max(ecg)-min(ecg)))', ':k');
% Hold off the figure
hold off
end
TO RUN THE CODE JUST TYPE <<ecgdemo IN COMMAND WINDOW
13. As you have already seenhow the ALGORITHM works,Lets seeits
implementationinMATLAB.
□ RUN M FILE
24. These Inputdata,Targetdata And Network Will Be Added Into Neural
Network/Data Manager(nntool)
Now CLICK Import
And ImportTheValues Which Are Provinding In MATLABCode.
□ Select InputData,TargetData,InitialInputStates,InitialLayer
States,OutputData And Error Data From The MATLAB WorkspaceIn
Order To TRAINthe NETWORK.
25. □ These All Will Be ImportIn Neural Network/Data Manager(nntool)
Just CLICK Network
26. Now We HaveTo TRAINThis Network
CLICK TRAIN
Select InputAnd Target Data
Then,
CLICK Train Network