What Are High-Pass and Low-Pass Filters?

Kristopher Johnson picture Kristopher Johnson · Aug 30, 2008 · Viewed 83.7k times · Source

Graphics and audio editing and processing software often contain functions called "High-Pass Filter" and "Low-Pass Filter". Exactly what do these do, and what are the algorithms for implementing them?

Answer

Hallgrim picture Hallgrim · Sep 17, 2008

Here is how you implement a low-pass filter using convolution:

double[] signal = (some 1d signal);
double[] filter = [0.25 0.25 0.25 0.25]; // box-car filter
double[] result = new double[signal.Length + filter.Length + 1];

// Set result to zero:
for (int i=0; i < result.Length; i++) result[i] = 0;

// Do convolution:
for (int i=0; i < signal.Length; i++) 
  for (int j=0; j < filter.Length; j++)
    result[i+j] = result[i+j] + signal[i] * filter[j];

Note that the example is extremely simplified. It does not do range checks and does not handle the edges properly. The filter used (box-car) is a particularly bad lowpass filter, because it will cause a lot of artifacts (ringing). Read up on filter design.

You can also implement the filters in the frequency domain. Here is how you implement a high-pass filter using FFT:

double[] signal = (some 1d signal);
// Do FFT:
double[] real;
double[] imag;
[real, imag] = fft(signal)

// Set the first quarter of the real part to zero to attenuate the low frequencies
for (int i=0; i < real.Length / 4; i++) 
  real[i] = 0;

// Do inverse FFT:
double[] highfrequencysignal = inversefft(real, imag);

Again, this is simplified, but you get the idea. The code does not look as complicated as the math.