Average Filters

An average filter is often used to reduce noise on an image by replacing each pixel with the average of the pixels in the neighborhood defined by the kernel. Mathematically, we compute the average filter by convolving an image against a kernel whose elements are 1 units and normalize by the size of the kernel. An example average kernel is given by:

$$ k = \frac {1}{9} \begin{pmatrix} 1 & 1 & 1 \\ 1 & 1 & 1 \\ 1 & 1 & 1 \end{pmatrix} $$

Let's demonstrate an example of average filtering using a $2D$ matrix. I will not show full calculation here as this is covered on the kernel and convolution section but I demonstrate the operation in python. Mathematically, the average filter of a $2D$ matrix is expressed as:

$$ \begin{pmatrix} 1 & 1 & 3 & 5 \\ 3 & 2 & 5 & 2 \\ 2 & 7 & 6 & 1 \\ 1 & 1 & 7 & 2 \\ 4 & 2 & 5 & 3 \end{pmatrix} * \frac {1}{9} \begin{pmatrix} 1 & 1 & 1 \\ 1 & 1 & 1 \\ 1 & 1 & 1 \end{pmatrix} = \begin{pmatrix} 1 & 1 & 2 & 1 \\ 2 & 3 & 3 & 2 \\ 2 & 3 & 3 & 2 \\ 2 & 3 & 3 & 2 \\ 1 & 2 & 2 & 2 \end{pmatrix} $$

Implementation in Python

import numpy as np
from scipy import ndimage
A = np.array([ [1, 1, 3, 5],
    [3, 2, 5, 2],
    [2, 7, 6, 1],
    [1, 1, 7, 2],
    [4, 2, 5, 3]])

kernel = np.ones(shape=(3,3))
ndimage.convolve(A, (1/9)*kernel, mode='constant', cval=1)
array([[1, 1, 2, 2],
    [2, 3, 3, 2],
    [2, 3, 3, 2],
    [2, 3, 3, 3],
    [1, 2, 2, 2]])