Impementing lowpass and highpass filter with cutoff frequency

149 Views Asked by At

I want to implement a function named passfilter which (taking input signal, cutoff frequency, filter kind and sampling rate). For the kind argument i want to have the option of 'lowpass' (remove frequencies > cutoff, let frequencies <= cutoff pass) and 'highpass' (remove frequencies < cutoff, let frequencies >= cutoff pass). I came up with this piece of code but i doesn't really work.

import os
import numpy as np
from matplotlib import pyplot as plt
from scipy import fft


def passfilter(arr, cutoff, kind='lowpass', srate=256):
'''Returns a complex array with a filtered version of the input signal'''
    freqs= fft.fftfreq(arr.size, d = srate )
    arr = fft.fft(arr)
    if kind == 'lowpass': arr [freqs > cutoff] = 0
    elif kind == 'highpass': arr [freqs < cutoff] = 0        
    arr = fft.ifft(arr)
    return arr

I tested it with this:

xs = np.linspace(0, 10, 1000)

arr = np.sin(xs) + 0.5 * np.sin(xs * 30) + 0.3 * np.sin(xs * 50)

plt.plot(arr, label='original')
plt.plot(passfilter(arr, 5, kind='lowpass').real, label='lowpass')
plt.plot(passfilter(arr, 5, kind='highpass').real, label='highpass')
plt.legend()
plt.show()

But for highpass i just get a static line at 0 and for lowpass the original funtion. Thanks in advance.

0

There are 0 best solutions below