Search code examples
matlabfilteraverageweighted-average

Matlab 3x3 weighted averaging filter


Following advise from another post, I created a basic 3x3 averaging filter as follows:

blurP = zeros(512, 512);
for i = 1:510
for j = 1:510
    sum = 0;
    for k = i:i+2
        for l = j:j+2
            sum = sum+P(k,l);
        end
    end
    blurP(i+1,j+1) = mean2(P(i:i+2,j:j+2));
end
end
imshow(P), figure, imshow(blurP, []);

I need to create a weighted filter with two options: One counts the center element (of the 3x3 grid) twice, thus giving me ten elements in total. The other has sixteen elements in total, with the center element counted four times and the adjacent ones counted twice—only the corner elements of the 3x3 grid are counted once.


Solution

  • The easiest option is to just use convolution (via the conv2 function). Then designing your kernels is a simple as writing out exactly what you described:

    kernel1 = [1 1 1
               1 2 1
               1 1 1]/10;
    blurP1 = conv2(P, kernel1, 'same');
    

    and

    kernel2 = [1 2 1
               2 4 2
               1 2 1]/16;
    blurP2 = conv2(P, kernel2, 'same');