You are on page 1of 5

Example of 2D Convolution

Here is a simple example of convolution of 3x3 input signal and impulse response
(kernel) in 2D spatial. The definition of 2D convolution and the method how to
convolve in 2D are explained here.

In general, the size of output signal is getting bigger than input signal, but we
compute only same area as input has been defined. Because we forced to pad zeros
where inputs are not defined, such as x[-1,-1], the results around the edge cannot be
accurate. Plus, the size of output is fixed as same as input size in most image
processing.

Input

Kernel

Output
Notice that the origin of impulse response is always centered. (h[0,0] is located at the
center sample of kernel, not the first element.)

Let's start calculate each sample of the output one by one.


First, flip the kernel, which is the shaded box, in both horizontal and vertical direction.
Then, move it over the input array. If the kernel is centered (aligned) exactly at the
sample that we are interested in, multiply the kernel data by the overlapped input
data.
The accumulation (adding these 9 multiplications) is the last thing to do to find out
the output value.
Note that the matrices are referenced here as [column, row], not [row, column]. M is
horizontal (column) direction and N is vertical (row) direction.
function B = convolve(A, k);
[r c] = size(A);
[m n] = size(k);
h = rot90(k, 2);
center = floor((size(h)+1)/2);
left = center(2) - 1;
right = n - center(2);
top = center(1) - 1;
bottom = m - center(1);
Rep = zeros(r + top + bottom, c + left + right);
for x = 1 + top : r + top
for y = 1 + left : c + left
Rep(x,y) = A(x - top, y - left);
end
end
B = zeros(r , c);
for x = 1 : r
for y = 1 : c
for i = 1 : m
for j = 1 : n
q = x - 1;
w = y -1;
B(x, y) = B(x, y) + (Rep(i + q, j + w) * h(i, j));
end
end
end
end

Save the following code with filename 'convolve.m'. And then create a new m-file and type this code :

clear; clc;
I = [4 4 3 5 4;
6 6 5 5 2;
5 6 6 6 2;
6 7 5 5 3;
3 5 2 4 4];
k = [0 -1 0;
-1 4 -1;
0 -1 0];
Hsl = convolve(I, k)
Watch at the result! You can also compare the result with the matlab toolbox command 'conv2'

Bnd = conv2(I,k,'same')
The both results are same :
Hsl =
6 3 -2 8 9
9 3 0 2 -3
2 0 2 6 -3
9 6 0 2 1
1 8 -6 5 9
Bnd =
6 3 -2 8 9
9 3 0 2 -3
2 0 2 6 -3
9 6 0 2 1
1 8 -6 5 9

You might also like