Examples of Convolutions¶
Definition and Calculation¶
The definition for the convolution \(G=F\star W\) of two discrete functions \(F\) and \(W\) is:
\[G[i,j] = \sum_{k=-\infty}^\infty \sum_{l=-\infty}^\infty F[i-k,j-l] W[k,l]\]
The recipe to calculate the convolution is:
- Mirror the function \(W\) in the origin to give function \(W^m[i,j]=W[-i,-j]\),
- then shift the weight function \(W^m\) to position \((k,l)\) in the image,
- pixelwise multiply the function and shifted weight function and
- sum all resulting values, this is the result of the convolution at point \((i,j)\).
Let’s do this for a simple example. Below you see a small image \(F\) and a weight function \(W\). Here we use the convention that when drawing weight functions (also called kernels) we assume it is defined over the infinite two dimensional domain, but we indicate only those values different from zero (note that points \((k,l)\) such that \(W[k,l]=0\) do not add to the convolution result, we simply can ignore those points).
In [1]: from scipy.ndimage import convolve;
In [2]: F = np.random.randint(0,10,(15,15)); print(F)
[[2 7 4 1 7 1 5 8 8 0 7 2 4 4 0]
[8 5 2 7 9 4 7 8 6 7 2 5 0 3 2]
[1 8 6 1 7 2 2 1 9 1 7 9 6 3 6]
[5 5 2 3 9 4 5 6 1 5 2 5 6 2 5]
[5 7 1 8 3 6 7 1 8 8 2 1 1 7 3]
[4 3 0 1 2 5 5 5 5 2 8 5 7 1 0]
[6 4 7 8 9 0 9 6 4 3 2 1 1 0 2]
[0 9 6 0 5 8 6 0 7 7 1 3 9 1 1]
[7 1 7 4 2 8 6 9 4 0 8 8 5 9 1]
[9 5 9 2 8 0 2 2 8 4 2 6 3 1 2]
[4 6 3 8 1 9 2 7 2 0 0 4 9 5 7]
[9 3 5 6 5 3 9 7 3 2 9 7 3 9 2]
[3 3 9 0 3 9 2 4 3 9 4 1 8 3 7]
[7 6 4 0 5 3 9 4 4 7 3 9 2 8 4]
[8 1 2 0 3 6 3 5 5 6 6 9 6 1 2]]
In [3]: W = np.ones((3,3))/9.0; print(W)