Sleep Apnea Detection Using ECG Analysis
Sleep Apnea Detection Using ECG Analysis
BACHELOR OF TECHNOLOGY
In
ELECTRONICS AND COMMUNICATION ENGINEERING
Submitted by
POTHUGANTI MANASA 23EG104C53
CHILUKAMARI KARTHIK 23EG104C08
SUTHOJU VAMSHI KRISHNA 23EG104C29
Under the esteemed guidance of
Dr. POLI LOKESHWARA REDDY, [Link]., Ph.D
Assistant Professor
Department of ECE
2
ACKNOWLEDGEMENT
It is indeed a great pleasure to thank all the people who had given support in
completion of the project.
We would like to express our deep sense of gratitude and respect to our project guide
Dr. Poli Lokeshwara Reddy, Assistant Professor, Department of Electronics and
Communication Engineering, for his encouragement, excellent guidance and kind
support during our project, without which it would not have been possible to complete
this work. We are thankful to him for being highly cooperative throughout our project
work.
We are extremely grateful to Prof. N. Mangala Gouri, Head of the Department of
Electronics and Communication Engineering, for her encouragement and support
throughout the project.
Special thanks are dedicated to Prof. [Link] Kumar, Dean School of Engineering,
who helped us for the successful completion of our project.
We are extremely grateful to Dr. Palla Rajeshwar Reddy, Chairman, Anurag Group
of Institutions, who encouraged and helped us for the successful completion of our
project.
It is our pleasure to express thanks to all the teaching and non-teaching staff of
Electronics and Communication Engineering Department for their excellent
monitoring and their suggestions that helped in the successful completion of
coursework for [Link], Program.
Finally, we thank our parents and the Almighty, whose divine grace provided us the
opportunity to do our project work according to our wish.
Project associates…….
3
DECLARATION
We hereby declare that the project report entitled, “FOURIER AND WAVELET
TRANSFORM BASED SLEEP APNEA DETECTION IN ECG SIGNALS”, is
the work done by us and submitted for the partial fulfillment of the requirements for
the award of the degree of Bachelor of Technology in Electronics and
Communication Engineering, under the guidance of Dr. Poli Lokeshwara Reddy,
[Link]., Ph.D,, Assistant Professor, Department of Electronics and Communication
Engineering, Anurag University.
We further declare that this project report has not been previously submitted before
either in part or full for the award of any degree or any diploma by any organization
or any universities.
Project associates…….
POTHUGANTI MANASA (23EG104C53)
CHILUKAMARI KARTHIK (23EG104C08)
SUTHOJU VAMSHI KRISHNA(23EG104C29)
4
ABSTRACT
Sleep apnea, a common sleep disorder characterized by interruptions in breathing during sleep,
poses significant health risks and can lead to various cardiovascular and neurological
complications. This project focuses on the development of a robust method for the detection of
sleep apnea using Electrocardiogram (ECG) signals. The proposed approach employs both
Fourier and wavelet transforms, integrating signal processing techniques to enhance detection
accuracy.
The initial phase of the project involves the application of a Butterworth bandpass filter to
preprocess the ECG signals, removing noise and isolating relevant frequency components. The
Fourier transform is then applied to compute the Power Spectral Density (PSD), capturing
frequency-domain features indicative of sleep apnea. Additionally, wavelet transform analysis
is performed to extract wavelet coefficients, offering time-frequency information that aids in
detecting apnea-related patterns.
Subsequent analysis involves the comparison of PSD and wavelet coefficients with dynamic
thresholds. These thresholds are adaptive and designed to identify significant deviations in
signal features, facilitating the detection of apnea and non-apnea events. By leveraging both
Fourier and wavelet-based analysis, this research provides a reliable and efficient
computational approach for sleep apnea detection, offering a non-invasive diagnostic tool for
early identification of individuals at risk.
Keywords: ECG, Fourier Transform, Wavelet Transform, Sleep Apnea Detection, Feature
Extraction, Power Spectral Density, Dynamic Thresholding.
5
CONTENTS
CERTIFICATE
ACKNOWLEDGEMENT
DECLARATION
ABSTRACT
CONTENTS
LIST OF FIGURES
LIST OF TABLES
LIST OF ABBREVIATIONS
CHAPTER-I
INTRODUCTION 1-9
6
1.5 Preproccessing approaches 6-7
CHAPTER-II
CHAPTER-III
CHAPTER-IV
4.1 Introduction 23
4.2 Methodology 25
4.2.2 Preprocessing 24
7
4.2.4 Threshold-Based Detection Of Apnea Events 25
CHAPTER-V
8
6.2 Preprocessing 38-39
CHAPTER-VII
7.1 Advantages 46
CHAPTER-VIII
REFERENCES 50-51
APPENDIX 51-56
9
LIST OF FIGURES
Figure No. Name of the Figure Page
No.
Fig 3.2.1 23
10
LIST OF TABLES
Table No. Name of the Table Page No.
Existing methods
ABBREVATIONS
ECG Electrocardiogram
11
CHAPTER - I
INTRODUCTION
A signal is a measurable quantity that varies with time, space, or another independent
variable. In simpler terms, it's a representation of information or data that changes
over a particular parameter, such as time. Signals can be found in various forms,
including audio, video, temperature, pressure, or even biological activities like the
electrical impulses in our bodies. Signals are mainly classified into two types. They
are Continuous time signals and discrete time signals.
[Link]-Time Signals:
[Link]-Time Signals:
12
In contrast to continuous-time signals, discrete-time signals are defined only at
specific time points. These signals are commonly obtained through sampling
continuous-time signals. Sequences of numbers and digital audio samples are typical
examples of discrete-time signals, frequently encountered in digital signal processing.
[Link] Signals:
Digital signals are discrete in both time and amplitude, often taking on quantized
values. These signals are essential in digital communication and computing systems,
where information is represented in a binary form. Digital signals include binary code,
digital images, and any data stored or transmitted in a digital format.
[Link] Signals:
Periodic signals exhibit a repetitive pattern at regular intervals. These signals are
characterized by their periodicity, allowing for the analysis of cyclical phenomena.
Examples encompass sine waves, square waves, and other waveforms commonly
encountered in signal processing and communications.
[Link] Signals:
Aperiodic signals lack a repeating pattern over time. These signals are crucial in
representing transient events and phenomena without a regular structure. Examples
include impulse signals, step functions, and other non-repeating waveforms.
[Link] Signals:
Deterministic signals have predictable and precisely defined behaviors. They are often
described using mathematical functions or equations, making them amenable to
analytical techniques. Deterministic signals are fundamental in areas such as control
systems and mathematical modeling.
13
[Link] Signals: Analog signals are continuous signals that can take on a range
of values. They are commonly found in natural phenomena and analog electronic
systems. Analog signals include voltage signals in electrical circuits and analog audio
signals.
[Link] Signals:
Binary signals are a specific type of digital signal that takes on only two discrete
levels or states. They form the basis of digital communication and computing, where
information is represented using binary code and conveyed through on/off states.
[Link] Signals:
1.2.1 Electrocardiogram(ECG)
The electrocardiogram (ECG) is a graphical representation of the heart's electrical
activity, recorded through electrodes placed on the skin. These electrodes detect the
small electrical changes caused by the polarization and depolarization of the heart's
cells during each heartbeat. Depolarization refers to the process where the heart's
muscle cells lose their electrical charge, leading to contraction, while repolarization is
the process of regaining the electrical charge, allowing the heart to relax. The ECG
captures these changes as distinct waveforms, such as the P wave (atrial
depolarization), QRS complex (ventricular depolarization), and T wave (ventricular
repolarization). By analyzing these waveforms, healthcare providers can diagnose
cardiac conditions like arrhythmias and myocardial infarction, and researchers can use
ECG signals to study physiological processes like heart rate variability and sleep
apnea detection.
14
their quality. It involves techniques like filtering to reduce noise, transforming
signals using methods like the Fourier transform for frequency analysis, and
feature extraction. In digital signal processing (DSP), signals are converted into
discrete data and processed using algorithms. Signal processing is crucial in
various fields, including communications, audio and image processing, and
biomedical engineering, where it plays a key role in applications like speech
recognition, image compression, and medical diagnostics.
[Link]:
Signal processing enhances clarity, reduces noise, and facilitates data
compression in telecommunication systems, ensuring efficient and reliable
communication.
2. Audio Processing:
It improves sound quality in music and speech, supports noise reduction, and
enables advanced voice recognition systems, contributing to clearer and more
accurate audio experiences.
3. Image and Video Processing:
Techniques in signal processing enhance image quality, enable effective image
compression, and support applications like facial recognition and computer
vision, which are essential for security and automated systems.
4. Biomedical Engineering:
In this field, signal processing is crucial for analyzing physiological signals such
as ECG and EEG. It aids in medical diagnostics, patient monitoring, and the
development of diagnostic tools.
5. Radar and Sonar:
15
Signal processing improves the detection and tracking of objects by filtering and
analyzing reflected signals, which is vital for navigation, surveillance, and
environmental monitoring.
6. Speech Processing:
It supports speech recognition and synthesis, enhancing applications such as
virtual assistants and transcription services by making interactions with
technology more intuitive.
7. Seismology:
Signal processing techniques are used to analyze seismic signals, helping to
monitor and understand earthquakes and other geological activities, which is
essential for disaster preparedness and research.
8. Control Systems:
Signal processing is integral to control systems for tasks such as feedback
control, filtering, and system identification, contributing to automation in
industries and robotics.
[Link] Networks:
Signal processing is used in sensor networks for extracting meaningful
information from sensor data, enabling applications in environmental
monitoring, smart cities, and industrial automation.
[Link] Signal Processing:
In finance, signal processing techniques are applied for analyzing financial time
series data, predicting market trends, and risk management.
[Link] Systems:
Signal processing techniques are applied in power systems for monitoring,
control, and fault detection, contributing to the stability and efficiency of
electrical grids.
[Link] Signal Processing:
In acoustics, signal processing is applied for tasks like noise cancellation, audio
recognition, and spatial audio processing.
[Link] Signal Processing:
16
Signal processing is used in environmental monitoring for analyzing signals
from sensors measuring air quality, water quality, and other environmental
parameters.
[Link] and Defense:
Signal processing is vital in radar systems, satellite communication, and
navigation systems for applications in aerospace and defense.
17
distortion. For ECG signals, a typical order is chosen to balance between
adequate attenuation of unwanted frequencies and minimal signal distortion.
Cutoff Frequencies: The cutoff frequencies are selected based on the specific
frequency range of interest in the ECG signal. For instance, to focus on the
frequency components relevant to sleep apnea, typical cutoff frequencies might
be set between 0.1 Hz to 30 Hz, depending on the noise characteristics and the
specific features of interest.
Implementation in MATLAB:
In MATLAB, the Butterworth filter can be designed using the butter function.
For example:
[b, a] = butter(order, [low_cutoff, high_cutoff] / (Fs / 2), 'bandpass');
filtered_ecg = filtfilt(b, a, raw_ecg);
Here, order is the filter order, low_cutoff and high_cutoff are the cutoff
frequencies, Fs is the sampling frequency, and raw_ecg is the original ECG
signal.
Hence, effective preprocessing using Butterworth Bandpass Filtering is essential
for enhancing the quality of ECG signals in sleep apnea detection projects. It
ensures that the subsequent analysis steps—Fourier and wavelet transforms—
are applied to clean and relevant data, thereby improving detection accuracy and
robustness.
18
Traditional methods often struggle to capture the subtle changes associated with sleep
apnea and may not be sufficient for reliable detection. This project addresses these
challenges by employing advanced signal processing techniques, specifically Fourier
and wavelet transforms, combined with robust preprocessing methods to improve the
accuracy of sleep apnea detection from ECG signals.
● Chapter I: Introduction
19
This chapter provides an introductory overview of sleep apnea detection,
highlighting the significance of accurate diagnosis and the role of ECG signals in
detecting sleep apnea. It also outlines the challenges associated with analyzing
ECG signals and the need for advanced signal processing techniques.
This chapter reviews existing research and methods related to sleep apnea
detection using ECG signals. It covers previous studies, discusses various signal
processing techniques, and highlights their strengths and limitations.
This chapter details existing methodologies for sleep apnea detection that are less
effective compared to the proposed approach. It includes a critique of traditional
methods and an explanation of why they fall short in addressing the challenges
posed by ECG signal analysis.
This chapter presents the proposed methodology for detecting sleep apnea. It
describes the preprocessing approach using Butterworth Bandpass Filtering, the
application of Fourier and wavelet transforms, and the dynamic thresholding
technique for event detection. It explains how these methods collectively enhance
the accuracy of sleep apnea detection.
This chapter discusses the software tools used in the project, specifically
MATLAB. It provides an overview of how MATLAB is utilized for signal
processing, feature extraction, and simulation of results.
This chapter presents the results obtained from the simulation of the proposed
methodology. It includes visual and quantitative analyses of the detected sleep
apnea events, comparisons with existing methods, and the evaluation of
performance metrics such as accuracy and sensitivity.
20
● Chapter VII: Advantages and Applications
This chapter outlines the advantages of the proposed methodology over existing
methods. It also explores potential applications of the detection system in clinical
settings, wearable devices, and other practical scenarios.
This chapter summarizes the key findings of the project, reiterates the significance
of the proposed methodology, and discusses the overall impact on sleep apnea
detection. It also includes recommendations for future work and potential
improvements.
CHAPTER – II
LITERATURE REVIEW
Quiceno-Manrique et al. [1] proposed a methodology to detect obstructive sleep
apnea (OSA) using electrocardiogram (ECG) recordings. The method applies time-
frequency analysis to heart rate variability (HRV) signals, which are extracted from
ECG data. They used Cohen’s class of quadratic time-frequency distributions to
analyze the HRV signals and extract dynamic features such as linear frequency
cepstral coefficients and spectral centroids. These features were then input into a k-
nearest neighbor (k-NN) classifier, which distinguished between normal and
pathological signals. The proposed system achieved an accuracy of up to 92.67% in
classifying one-minute intervals of ECG data. This approach allows for a simplified
diagnosis tool for OSA, using a non-invasive and cost-effective method compared to
standard polysomnography.
In the study by L. Hejjel and I. Gál [2], the authors provided an in-depth analysis of
heart rate variability (HRV) through both time-domain and frequency-domain
methods. The HRV fluctuations, controlled by sympathetic and parasympathetic
21
influences, were used to assess autonomic nervous system functioning under various
conditions such as stress, posture changes, and disease states. The study demonstrated
the importance of spectral analysis methods like Fast Fourier Transform (FFT) in
HRV evaluation and highlighted the potential clinical applications of HRV in
monitoring cardiovascular health, predicting disease outcomes, and assessing physical
and mental stress levels.
J.A. Fiz, et al. [3] proposed an acoustic analysis of snoring sounds in patients with
simple snoring and obstructive sleep apnoea (OSA). The study analyzed the snoring
sound power spectrum of 17 male patients (10 with OSA and 7 with simple snoring)
using full-night polysomnography. Two distinct acoustic patterns were observed,
distinguishing OSA patients from simple snorers based on snoring frequency. OSA
patients had significantly lower peak frequencies, with a negative correlation between
the apnoea-hypopnoea index (AHI) and snoring sound frequencies. This analysis
offers potential for developing a tool for distinguishing OSA from simple snoring.
Margot Deviaene et al. [5] proposed a classification algorithm for detecting sleep
apnea using pulse photoplethysmography (PPG) signals. The algorithm is based on a
least-squares support vector machine (LS-SVM) and processes features derived from
22
PPG, including pulse rate and amplitude variability. The model was trained and tested
on polysomnographic data from 102 subjects suspected of sleep apnea. The results
showed that using PPG alone yielded a classification accuracy of 68.7%. When
combined with oxygen saturation (SpO2) features, the accuracy improved to 83.4%,
slightly better than using SpO2 alone. Although PPG features are promising, their
added value beyond SpO2 is limited.
Majdi Bsoul, et al. [7] proposed a real-time sleep apnea monitoring system, called
Apnea MedAssist, which utilizes single-lead ECG data. The system extracts features
from the nocturnal ECG of patients and employs support vector classifiers (SVC) to
detect obstructive sleep apnea (OSA) episodes. The system runs on Android
smartphones and offers two SVC models: subject-independent and subject-dependent.
The study reported an F-measure of 90% and 96% sensitivity for the subject-
independent SVC, making it suitable for home and clinical applications for detecting
OSA.
Kaicheng Feng et al. [8] proposed a sleep apnea detection method using single-lead
ECG signals, focusing on unsupervised feature learning. The method is based on a
frequential stacked sparse autoencoder (FSSAE) for automatic feature extraction and
a time-dependent cost-sensitive (TDCS) classification model, which combines the
Hidden Markov Model (HMM) and the MetaCost algorithm. The approach aims to
23
improve classifier performance by addressing data imbalance and considering
temporal dependencies. The model was trained on polysomnographic data and
achieved 85.1% accuracy, 86.2% sensitivity, and 84.4% specificity. The study
highlights that ECG-based sleep apnea detection using unsupervised learning can
provide a viable and efficient alternative to traditional methods.
24
S. Journal Title Methodology Advantages Limitations
Name/Vol./
No.
Page No.
Year
25
Table 2.1 Summary of Literature Review
CHAPTER – III
EXISTING METHODS
Sleep apnea is detected by different methods and processes, different therapies are
used to treat the apnea. Following are the existing techniques for detection and
treatment of sleep apnea:
Sleep apnea is a condition where a person’s breathing repeatedly stops and starts
during sleep. This can lead to poor sleep quality and other health problems like heart
disease and high blood pressure.
Sleep apnea is a condition where a person’s breathing repeatedly stops and starts
during sleep. This can lead to poor sleep quality and other health problems like heart
disease and high blood pressure.
Autoregressive (AR) models are a way of predicting a future value of a signal based
on its past values. In simple terms, they look at the recent history of the signal to
make a prediction about its next step. For example, in sleep apnea detection, an AR
model can analyze a signal like heart rate or breathing pattern to see if there’s a
repeated abnormal pattern, which may signal an apnea event. The model assumes that
past values are a good indicator of what will happen next, making it useful for
analyzing time-dependent data. AR models work by expressing the current value of
the signal as a linear combination of its previous values plus a noise term. The order
of the model, which determines how many past values are used, is crucial for
accuracy and can be selected using criteria like the Akaike Information Criterion
(AIC) or Bayesian Information Criterion (BIC).
26
In sleep apnea detection, AR models can be particularly useful for identifying
deviations from normal breathing patterns or heart rate variability. During an apnea
event, the model may detect significant changes, indicating a potential apnea episode.
One of the advantages of AR models is their simplicity and computational efficiency,
making them suitable for real-time monitoring systems. However, they assume that
the signal is stationary, which can be a limitation for non-stationary signals. To
improve accuracy, AR models can be combined with other techniques such as
machine learning algorithms, which can learn complex patterns from large datasets.
Additionally, preprocessing steps like detrending and differencing can help in
handling non-stationary signals.
3.2 Periodogram
A periodogram is a tool used to find out which frequencies are present in a signal and
how strong they are. It transforms the signal from the time domain into the frequency
domain, helping us see if there are any dominant frequencies that repeat over time. In
sleep apnea detection, a periodogram can analyze a person's breathing or heart rate to
find abnormal frequency patterns, like those caused by interrupted breathing.
However, it’s not always the best tool for complex signals because it can struggle to
clearly separate close frequencies or deal with rapidly changing signals. To overcome
these limitations, techniques like the Short-Time Fourier Transform (STFT) or
wavelet transforms can be used, which provide better time-frequency resolution and
are more effective for non-stationary signals. Moreover, combining periodograms
with machine learning algorithms can enhance the detection accuracy by learning
patterns from large datasets.
27
FIG 3.2.1
Flexibility:
Dependencies: Effective in May not capture complex
modeling and identifying or non-linear
patterns in time-series data relationships
Requires Parameter
Simple and computationally Tuning: Choice of model
efficient: relatively order (number of lags)
straightforward to implement can affect performance
and interpret and needs careful
selection.
Periodogram Simple to Compute: Provides a Poor Frequency
straight-fo rward estimation Resolution: Limited
of the power spectral density ability to distinguish
of a signal closely spaced
frequencies.-
28
Widely applicable : can be No Time information on :
used in various domains for lacks the capability to
frequency analysis. analysis how frequency
content changes over time
.
CHAPTER-IV
PROPOSED METHODOLOGY
4.1 Introduction This project proposes a methodology for detecting sleep apnea
using ECG signals. The approach uses advanced signal processing techniques,
including bandpass filtering, feature extraction from frequency components, and
dynamic thresholding for apnea classification. The methodology aims to enhance the
accuracy of apnea detection while maintaining robustness across different subjects.
The following sections detail the various steps involved, supported by mathematical
analysis, a block diagram, and the performance metrics used for evaluation.
4.2 Methodology
The first step is collecting ECG signals from a reliable source, such as a publicly
available sleep apnea database (e.g., PhysioNet’s Apnea-ECG Database). This dataset
contains long-duration ECG recordings during sleep from both normal subjects and
29
individuals diagnosed with sleep apnea. These ECG signals serve as the input to the
system for analysis.
ECG signals often contain noise and unwanted components, such as baseline wander
and power-line interference. A Butterworth bandpass filter is used to remove these
elements while retaining the frequency components relevant to sleep apnea. The filter
is set with a low cutoff frequency to remove slow variations and a high cutoff
frequency to eliminate high-frequency noise.
1
H ( s )=
( )
2n
The Butterworth filter transfer function is given as: s
√ 1+
ωc
For this project, the bandpass filter is designed with a range of 0.1 Hz to 30 Hz, which
effectively retains the key ECG signal components while removing irrelevant noise.
Once the signal is filtered, frequency-domain features are extracted using the Fourier
Transform. The Fourier Transform decomposes the signal into its frequency
components, allowing for the calculation of the Power Spectral Density (PSD), which
represents the power distribution of the signal over various frequencies.
2
From this, the PSD can be calculated as: | X ( ω )|
The PSD provides essential information about the dominant frequency components of
the signal, which are used to detect abnormalities associated with sleep apnea.
30
[Link] Wavelet Coefficients via Wavelet Transform
( t−ba ) dt
The continuous wavelet transform is given by: W ( a , b )=∫ x ( t ) ψ∗
−∞
Where ψ is the mother wavelet, ( a) is the scale, and ( b ) is the translation parameter.
The extracted wavelet coefficients provide information about the signal's energy at
different frequency levels, which is then used for feature extraction.
Once the relevant features (PSD from the Fourier Transform and wavelet coefficients
from the wavelet transform) are extracted, a dynamic threshold is applied to classify
the data. The threshold is adaptive and changes based on the characteristics of the
signal, making it sensitive to individual variations in the ECG signal.
By comparing the extracted features with the threshold, the system identifies whether
the signal segment indicates an apnea event or normal breathing.
The final step in the methodology is to classify each segment of the ECG signal as
either an apnea event or non-apnea event. If the extracted features exceed the dynamic
threshold, the segment is classified as an apnea event. Otherwise, it is classified as
non-apnea. This binary classification is performed based on the extracted PSD and
wavelet coefficients.
31
Accuracy: Measures the overall correctness of the classification
TP+TN
Accuracy =
TP+ TN + FP+ FN
Sensitivity: Measures the ability of the system to correctly identify apnea events.
TP
Sensitivity =
TP+ FN
Specificity: Measures the ability of the system to correctly identify non-apnea events.
TN
Specificity =
TN + FP
32
CHAPTER-V
SOFTWARE DESCRIPTION
5.1 Introduction
In this project, use the software MATLAB to execute the required results. MATLAB
(matrix laboratory) is a fourth-generation high-level programming language and
interactive for numerical, visual and programming.
● Matrix manipulations
● Plotting of functions and data
● Implementing of algorithms
● Creation of user interface
The basic building block of MATLAB is MATRIX. The fundamental data type is the
array. Vectors, scalars, real matrices and complex matrices are handled as specific
classes of this basic data type. The built in functions are optimized for vector
operations. No dimension statements are required for vectors or arrays.
MATLAB Window
The MATLAB works based on five windows: Command window, Workspace
window, Current directory window, Command history window, Editor Window,
Graphics window and Online-help window.
33
● Command Window: In this command window it displays a command
prompt
“>>” and the cursor starts blinking where the commands can be entered and
executed. For example we try some arithmetic expressions.
34
Fig 5.1: (b) Command Window Showing Values
As shown in the Figure5.1 (b). a is initialized one value and b also with some value. z
is having the value of a +b. Workspace is a collection of all variables.
a = 10 and b =20 z = a+b =30
35
● Command History Window: The Command History Window contains a
record of the commands a user has entered in the command window,
including both current and previous MATLAB sessions. Previously entered
MATLAB commands can be selected and re-executed from the command
history window by right clicking on a command or sequence of commands.
This is useful to select various options in addition to executing the commands
and is a useful feature when experimenting with various commands in a work
session.
● Editor Window: Editor Window is to create a new file and to edit the saved
page. We can create a new file and can also open an existing file here; the
files saved with the .m extension are called M-files.
● Graphics or Figure Window: The output of all graphic commands typed in
the command window is seen in this window.
● Online Help Window: MATLAB provides online help for all its built in
functions and programming language constructs. To know about any function
or the command click on the help icon so that we can easily find out the
command description. To check the proper command or function at a
particular line click on the help command and look for command.
5.2.2 MATLAB Files
● M-Files
These are standard text files with ‘m’ extension to the file name and creating their
own matrices using M-files, which are text files containing MATLAB code.
MATLAB editor or another text editor is used to create a file containing the same
statements which are typed at the MATLAB command line and save the file under a
name that ends in .m. There are two types of M-files:
● Script Files
It is an M-file with a set of MATLAB commands in it and is executed by typing the
name of the file on the command line. These files work on global variables currently
present in that environment.
● Function Files
36
A function file is also an M-file except that the variables in a function file are all
local.
Required clc:
(Clear Command Window) This syntax clears all the text displaying in the Command
Window which clears the entire screen.
clear:
Here it removes all the variables and functions from the workspace. For example, if
we consider three variables of x, y, z initializing some values as p = 1; q = 2; r = 3;
clear p;
Only one variable p is cleared from the workspace and the remaining two variables q
and r displays in the workspace.
uigetfile: There is different syntax to get a single or multi file. This uigetfile displays
a dialog box for retrieving files. In this project after running the main file it displays a
dialog box to select the file. Here, this project is on underwater image enhancement so
we select an input image. After selecting an input image click on the open button.
[filename, pathname] = uigetfile (...);
imread: imread is initialized to read images from the file. There are
different syntaxes to read an image. Here we used a single image in
this project so to read that image we use syntax
inp = imread(fname);
Some of the formats to read an image gif, jpg or jpeg, tif or tiff etc.
37
A = imread (filename, fmt);
Reads an image from the file specified and the format of the file is also mentioned in
the above syntax as imread (filename, fmt).
size:
To know the size of the image in array dimensions the syntax is written in M and N
as rows and columns.
[M N] = size (inp)
imshow:
38
imwrite write image to graphics file. imwrite (a, filename, fmt) writes the image a to
the file specified by filename in the format specified by fmt. a can be an m-by-n
(grayscale image) or m-by-n-by-3 (color image) array, a cannot be an empty array. if
the format specified is tiff, imwrite can also accept an m-by-n-by-4 array containing
color data that uses the cmyk color space. imshow display image in handle
graphics figure. imshow (i) displays the gray scale image i.
sqrt:
Which gives the square root value for example if we initialize f = 25 then to get the
square root value of f then we have to use the syntax as
>>f = 25 f= 25
end:
To terminate any block of the code then the end is used. If we use any of these for,
while, switch, if, and try then we end the block by using end syntax. Generally the
loops are used to check any conditions according to the program. To terminate the
block and go to the next line we close the block with the end.
39
In this project a single image is given as input image and our white-balancing
approach derived into two images one is the input 1 and input 2 as shown in the
Figure using gamma correction and edge sharpening and the two input images are
used as inputs of the fusion process. Multi-scale fusion approach is here to examine
with three levels by weight maps calculation.
Advantages
● It is a case sensitive language
● MATLAB does not require a compiler to execute.
● It is an object oriented language.
Disadvantages
● It is very costly and the user has to buy each and every module.
40
● It is very difficult during cross compiling.
● It uses a large amount of memory.
● Click on open and select the source file from the drive. Select the source file and
click on the open button then the source file opens in the current folder. Click on
+ sign to see the files present in the folder. If a source file is to be selected or to
be added to the current folder click on file in the toolbar present at the top.
● Select the source file and click on the open button. As shown in the Figure 5.4.
(c).code file is selected and click on open.
● In the current folder it displays our code source file. Double click on the file it
displays the main file and the image which is going to be our input image.
41
Figure 5.4: (a) MATLAB Layout
Click on open and select the source file from the drive. Select the
source file and click on open button then the source files opens in the
current folder. Click on + sign to see the files present in the folder. If
a source file is to be selected or to be added to the current folder click
on file in the tool bar present at the top.
Select the source file and click on open button. As shown in the
Figure5.4.(c).code file is selected and click on open.
After clicking on code file the file is going to display in the current
42
folder list.
In current folder it displays our code source file. Double click on the file
it displays the main file and the image which is going to be our input
image.
Click on main file as shown in the Figure5.3. (d). Run the main file it
displays a dialog box to select the input file
CHAPTER-VI
43
capability of the system to detect sleep apnea through a combination of Fourier and
wavelet transforms, supported by dynamic thresholding.
The ecg signals of two individuals, person 1 suffering with moderate apnea and
person 2 suffering with severe apnea are taken and plotted in MATLAB.
44
The ECG signal was filtered using Butterworth Bandpass filter with cutoff
frequencies of 0.1Hz and 30Hz to remove noise and artifacts.
PERSON 1:
PERSON 2:
FIG:Filter
ed ECG signal of person 2 with apnea
45
6.3 Feature Extraction
6.3.1 Fourier Transform Analysis: The Fourier Transform was applied to calculate
the power spectral density (PSD) of the preprocessed ECG signals
Person 1:
FIG:
Person 2:
46
FIG:
The Wavelet Transform was used to decompose the ECG signal ,capturing both time
and frequency information.
Person 1:
47
FIG:
48
PERSON 2:
FIG:
Using the features extracted and setting threshold with the outliers code in MATLAB
the potential sleep apnea events in each signal are plotted.
PERSON 1:
49
FIG:
PERSON 2:
50
FIG: Signal with Apnea episodes highlighted
51
CHAPTER- VII
7.1 Advantages
3. Improved Accuracy: By analyzing both time and frequency domains, the system
enhances detection accuracy, identifying apnea events more precisely.
5. Real-time Detection: The system enables rapid detection, analyzing patterns and
signal features to flag apnea episodes as they occur.
7.2 Applications
1. Clinical Diagnostics: Used in medical settings for the analysis of ECG data to
diagnose sleep apnea, improving patient outcomes.
52
2. Home-based Monitoring: This system can be integrated into wearable devices for
at-home monitoring, providing patients with convenience and continuous oversight.
53
CHAPTER – VIII
Looking ahead, several avenues provide opportunities for advancing and expanding
the system for sleep apnea detection using ECG signals:
Firstly, ongoing research is needed to refine and enhance the accuracy of the
detection algorithms, optimizing the performance in diverse patient populations and
conditions. The incorporation of machine learning could further improve the
adaptability and precision of the system, allowing it to identify more subtle apnea
patterns.
54
model's performance ensures that the system can offer more precise and
individualized diagnoses as data accumulates.
Validation studies, including large-scale clinical trials, are essential to strengthen the
system’s reliability and demonstrate its applicability across diverse patient groups.
These trials would not only ensure that the system meets stringent regulatory
standards but also facilitate its integration into clinical practice. By proving the
system's effectiveness in a controlled setting, it opens the door for widespread
adoption, helping to ensure that the technology can benefit a broader population.
As this technology advances, ensuring data security and privacy becomes crucial.
Remote monitoring and the transmission of sensitive health data require robust
safeguards to protect patient confidentiality and comply with legal standards.
Incorporating strong data protection measures will be vital to gaining trust from both
healthcare professionals and patients. Secure data handling will not only ensure
compliance with regulatory requirements but also foster confidence in the system's
reliability and integrity.
55
machine learning, rigorous validation, and secure data management, this methodology
stands to become a vital tool in the early detection and treatment of sleep apnea. Its
future integration into wearable devices and personalized healthcare solutions further
underscores its potential to significantly improve patient outcomes. By collaborating
with healthcare providers, this system will continue to evolve and contribute to the
broader field of healthcare technology, offering accessible, accurate, and personalized
solutions for sleep apnea patients.
REFERENCES
[1] Quiceno-Manrique et al. Detection of Obstructive sleep apnea in ECG recordings
using time-frequency distributions and dynamic features. IEEE international
conference on engineering in medicine And biology society (EMBC),(pg no:5559-
5562,2009)
[2] L. Hejjel and I. Gál Heart rate variability analysis Acta Physiologica Hungarica,
Volume 88 (3-4), pp. 219–230, 2001
[3] J.A. Fiz, et al Acoustic analysis of snoring sound in patients with simple snoring
and obstructive sleep apnea European Respiratory Journal, Vol. 9, pp. 2365–2370,
1996
[4] P. Janbakhshi and M.B. Shamsollahi Sleep Apnea Detection from Single-Lead
ECG Using Features Based on ECG-Derived Respiration (EDR) Signals IRBM, Vol.
39, pp. 206–218, 2018
[5] Margot Deviaeneet al. Sleep Apnea Detection Using Pulse Photoplethysmography
Computing in Cardiology 2018; Vol 45 Page 1
[6] Yuliya Zhivolupova Apnea MedAssist: Real-time Sleep Apnea Monitor Using
Single-Lead ECG IEEE Transactions on Information Technology in Biomedicine,
Vol. 15, No. 3, May 2
[7] Majdi Bsoul, et al. Sleep Apnea and Hypopnea Detection Algorithm Journal
2019 Ural Symposium on Biomedical Engineering, Radioelectronics and Information
Technology (USBEREIT), pp. 92-93
56
[8] Kaicheng Feng et al. A Sleep Apnea Detection Method Based on Unsupervised
Feature Learning and Single-Lead Electrocardiogram IEEE Transactions on
Instrumentation and Measurement, Vol. 70, 2021, 4000912
APPENDIX
SOURCE CODE
% Extract the variable 'val' (change if needed based on actual variable names)
if isfield(data, 'val')
signal = [Link];
else
error ('Variable "val" not found in the .mat file.');
end
% Remove NaNs and Infinities from the signal
signal = signal(~isnan(signal) & isfinite(signal));
57
high_cutoff = 30; % High cutoff frequency
% Fourier Transform
N = length(filtered_signal);
if N < 2
error ('Filtered signal is too short for FFT.');
end
58
f = (0:N-1) *(fs/N); % Frequency range
Y = fft(filtered_signal);
P2 = abs(Y/N); % Two-sided spectrum
P1 = P2(1:ceil(N/2) +1); % Single-sided spectrum
P1(2: end-1) = 2*P1(2: end-1); % Adjust amplitude
psd = (1/(fs*N)) * abs(Y). ^2; % Power Spectral Density
% Plot FFT
figure;
plot (f (1: ceil(N/2) +1), P1);
title ('Single-Sided Amplitude Spectrum of Filtered Signal');
xlabel('Frequency (Hz)');
ylabel('|P1(f)|');
% Wavelet Transform
if length(filtered_signal) > 0
[wt, f_wt] = cwt(filtered_signal, 'amor', fs); % Continuous Wavelet Transform
wavelet_coeff = abs(wt); % Magnitude of wavelet coefficients
59
colorbar;
else
warning ('Filtered signal is too short or contains invalid values for wavelet
transform.');
end
% Feature extraction
features = [mean(psd), std(psd), mean(wavelet_coeff(:)), max(wavelet_coeff(:))];
for i = 1:num_windows
start_idx = (i-1) *step_size + 1;
end_idx = start_idx + window_size - 1;
segment = filtered_signal(start_idx:end_idx);
60
[wt_segment, ~] = cwt(segment, 'amor', fs);
wavelet_coeff_segment = abs(wt_segment);
61
% Display classification summary
num_apnea_episodes = sum(classification_labels) / fs;
disp(['Total Apnea Duration: ', num2str(num_apnea_episodes), ' seconds']);
62