I want to prove (or more precisely experiment with) the idea that a 2D convoltion as produced by the Matlab conv2() function between an image I (2D matrix) and a kernel (smaller 2D matrix) can be implemented as some 1D conv i.e. the Matlab conv() function and NOT conv2(). Of course possibly some reshapes and matrix multiply might be needed but no conv2().
And to make it clear, I am NOT refering to that kind if thing:
s1=[1,0,-1]'
s2=[1 2 1]
diff=conv2(x,y)-conv2(conv2(x,s1),s2)
diff is = 0 everywhere
Rather, I want to do something like
conv(conv(x(:), filter1)filter2) ...
Answer
When a 2D filter $h[n,m]$ is separable; i.e., $h[n,m] = f[n]g[m]$, then the 2D convolution of an image $I[n,m]$ with that filter can be decomposed into 1D convolutions between rows and columns of the image and the 1D filters $f[n]$ and $g[m]$ respectively.
Let me give you the MATLAB / OCTAVE code, I hope this is what you wanted to show ?
clc; clear all; close all;
N1 = 8; % input x[n1,n2] row-count
N2 = 5; % input x[n1,n2] clm-count
M1 = 4; % impulse response h[n1,n2] row-count
M2 = 3; % impulse response h[n1,n2] clm-count
L1 = N1+M1-1; % output row-count
L2 = N2+M2-1; % output clm-count
x = rand(N1,N2); % input signal
f = rand(1,M2); % f[n1] = row vector
g = rand(M1,1); % g[n1] = column vector
h = g*f; % h[n1,n2] = f[n1]*g[n2]
y = zeros(L1,L2); % output signal
% S1 - Implement Separable Convolution
% ------------------------------------
for k1 = 1:N2 % I - Convolve COLUMNS of x[:,k] with g[k]
y(:,k1) = conv(x(:,k1),g); % intermediate output
end
for k2 = 1:L1 % II- Convolve ROWS of yi[k,:] with f[k]
y(k2,:) = conv(y(k2,1:N2),f);
end
% S2 - Matlab conv2() :
% ---------------------
y2 = conv2(x,h); % check for matlab conv2()
% S3 - Display the Results
% ------------------------
title('The Difference y[n,m] - y2[n,m]');
No comments:
Post a Comment