# Fourier Transform of ECG signal in Python

I have an ECG signal which I am analyzing using Python, as opposed to the mainstream MATLAB. So, I have digital form ECG in .dat file with .hea (header file). Below is the Fourier transform

The problem, as you can see, that it is not the correct Fourier transform. Below is my code.

import wfdb
import matplotlib.pyplot as plt
import numpy as np
from scipy import signal
from scipy import fftpack

cutoff = float(input("Cutoff: "))
cutoff = cutoff/(360.)
noiseAmp = float(input("Noise Amplitude: "))
programed_to = 5000

# load the aami3a ECG signal using special package wfdb for python.
record = wfdb.rdrecord('aami3a', sampto=programed_to, physical=False) # digital data, hence physical=False

# 2D numpy array storing the actual signal data. record is an object of wfdb which has many attributes.
# one of those attributes fs (sampling frequency) and d_signal which stores the amplitude at various times.
original = record.d_signal
# define time of 5000 length
t = np.arange(0, (1/record.fs)*programed_to, 1/record.fs)
# define a sinusoidal noise.
noise = noiseAmp*np.cos(2*np.pi*50*t)

# add noise to the ecg signal
record.d_signal = record.d_signal.flatten() + noise
# make the signal again a 2D array.
record.d_signal = np.reshape(record.d_signal, (-1, 1))

# define a fifth order butterworth lowpass filter with cutoff/fs/2 = 0.11 (tunable).
b, a = signal.butter(5, cutoff, 'lowpass', False)
# apply this low pass filter on the noisy ecg.
output_signal = signal.filtfilt(b, a, record.d_signal.flatten())

# plotting the FFT of the signal
# fft of the original signal.
org_fft = np.fft.fft(original)
freq = np.fft.fftfreq(original.size, 1/720.)
f1 = plt.figure()
A1.plot(freq, np.abs(org_fft))
plt.show()


• Why is that not the "right Fourier transform"? Can you elaborate on what the problem with that plot is? – Marcus Müller Nov 13 '18 at 12:24
• Because, there would be a single peak at 0 frequency. – Himanshu Sharma Nov 13 '18 at 12:27
• Absolutely not, unless you're only observing noise and the patient has been dead for quite a while. – Marcus Müller Nov 13 '18 at 14:21

Ok, so a little trick and the transform would be correct. The problem is on last 6th line. Instead of np.fft.fft(original), it should be np.fft.fft(np.array(origitnal).flatten()). I think that the wrong results were because original was a 2D numpy array.