I'm looking for a method to compute the same result that conv2 will give, by using conv in MATLAB. (I'm doing the convolution in C code and I need to compare the result between MATLAB and my code.)
I have heard that it's possible to use 1D convolutional vector multiplication to achieve the same result as 2D convolutional matrix multiplication, only if the kernel K is separable e.g gaussian kernel. Also, by doing this way, 1D-way is much faster than computing the 2D way.
Here I have collected some Matlab code:
% Create data
A = randn(10, 10);
% Create gaussian kernel
sigma = 1;
kernel_size = round(6 * sigma);
% Create mesh grid
[x, y] = meshgrid(-kernel_size:kernel_size, -kernel_size:kernel_size);
% Create gaussian 2D kernel
K = 1/(2*pi*sigma^2)*exp(-(x.^2 + y.^2)/(2*sigma^2));
I wonder how I can achieve the same result as conv2(A, K, 'same') if I'm using conv only. Should I first do conv(A(i, :); K(i, :), 'same') for each row and then conv(A(:, i); K(:, i), 'same') for each column?
If the 2-D kernel
Kis separable into a row vectorkrand a column vectorkcsuch thatK = kc*kr, the result ofconv2(A, K, 'same')can be obtained more efficiently asconv2(kr, kc, A, 'same')(or equivalently asconv2(kc, kr, A, 'same')).If you need to use only
conv, you have to convolve each row ofAwithkr, and then each column of the result withkc(or equivalently in the opposite order).So, in your example:
you can obtain the same result with
Check:
gives a value of the order of
eps, so the two results are the same up to floating-point inaccuracies.