Dienstag, 3. November 2015

CONVOLUTION IN MATLAB

                 Let us try to understand convolution by performing spatial averaging on a matrix without using MATLAB built in function ‘conv2()’.

%CONVOLUTION IN MATLAB

%INPUT  MATRIX
A = zeros(5);
A(:) = 1:25;

%KERNEL
avg3 = ones(3)/9;

%CONVOLUTION
Result = conv2(A,avg3,'same');
display(Result);

Steps to be performed:





NOTE :
To define a kernel for spatial averaging, fill the kernel with ones and divide it by the number of elements in it.
For instance, consider kernel of size 4x4 , fill the  matrix with ones and divide it by 16. i.e the total number of elements in the matrix.

MATLAB CODE:
%INPUT  MATRIX
A = zeros(5);
A(:) = 1:25;

%KERNEL
avg3 = ones(3)/9;

%PAD THE MATRIX WITH ZEROS
B = padarray(A,[1 1]);
% PRE-ALLOCATE THE MATRIX
Output = zeros([size(A,1) size(A,2)]);

%PERFORM COONVOLUTION
for i = 1:size(B,1)-2
    for j = 1:size(B,2)-2
        Temp = B(i:i+2,j:j+2).*avg3;
        Output(i,j) = sum(Temp(:));
    end
 end

display(Output);

Keine Kommentare:

Kommentar veröffentlichen