Filters are often used in signal processing from the perspective of noise reduction. Implement the simplest FIR filter in Python and C. It is assumed that the filter is evaluated based on Python and the result is incorporated into a C language-based application.
The implementation of the FIR filter using scipy is shown below. The original signal x
is a random number, and the filter coefficient is calculated by scipy.signal.firwin
. Compare the signal y
after applying the filter by scipy and the signal d
after applying the filter by solid.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
import numpy as np
import scipy.signal
from pylab import *
import csv
import matplotlib.pyplot as plt
#x can be anything
x = np.random.rand(512)
plt.plot(x)
plt.show()
fs = 512 #Sampling frequency
nyq = fs / 2.0 #Nyquist frequency
#Filter design
f1 = 1 / nyq #Cutoff frequency 1
f2 = 30.0 / nyq #Cutoff frequency 2
numtaps = 255 #Number of filter coefficients(Odd)
b = scipy.signal.firwin(numtaps, f1) #Low pass
#b = scipy.signal.firwin(numtaps, f2, pass_zero=False) #High pass
#b = scipy.signal.firwin(numtaps, [f1, f2], pass_zero=False) #Bandpass
#Saving filter coefficients
with open('coeff.csv', 'w') as f:
writer = csv.writer(f, lineterminator='\n') #Line feed code (\n) is specified
writer.writerow(b)
#FIR filter by scipy
y = scipy.signal.lfilter(b, 1, x)
#FIR filter by solid writing
d = np.zeros(fs)
for i in range(len(x)):
d[i] = 0
for j in range(len(b)):
if(i-j)>=0:
d[i] += b[j]*x[i-j]
plt.plot(y,color='r')
plt.plot(d,color='b')
plt.show()
Original signal
After applying the filter (red: y, blue: d)
If the solid result on Python is correct, drop it into C language code. It's a little rough, but b
stores an array of coeff.csv generated by Python code. Since it is saved in csv format, if you open it with a text editor etc., you can copy and paste it as it is.
int sampleRate = 512
x= //Although it is rough, describe x appropriately
float* filteredData = (float*)malloc(sizeof(float)*512);
float b[] = {} //Rough, but coeff written in Python.Insert the contents of csv in parentheses
for(int i=0;i<sampleRate;i++){
float d = 0;
for(int j=0; j<(sizeof b)/(sizeof b[0]); j++){
if((i-j)>=0){
d += b[j]*x[i-j];
}
}
filteredData[i]=d;
}
free(filteredData)
It's very simple, but it's just a memorandum, so forgive me, how do you implement an FIR filter? If it helps someone who says.
Recommended Posts