hamza zubair gondal
hamza zubair gondal

Reputation: 23

Average filter Matlab

I have written the 3x3 average filter. It works fine but it shows the same output image three times instead of one. How to resolve the problem?

The code is

function [filtr_image] = avgFilter(noisy_image)

    [x,y] = size(noisy_image);
    filtr_image = zeros(x,y);
    for i = 2:x-1
        for j =2:y-1
            sum = 0;
            for k = i-1:i+1
                for l = j-1:j+1
                    sum = sum+noisy_image(k,l);
                end
            end
            filtr_image(i,j) = sum/9.0;
           filtr_image = uint8(filtr_image);

        end
    end

end

thanks in advance

Upvotes: 2

Views: 2476

Answers (2)

rayryeng
rayryeng

Reputation: 104464

What is most likely happening is the fact that you are supplying a colour image when the code is specifically meant for grayscale. The reason why you see "three" is because when you do this to allocate your output filtered image:

[x,y] = size(noisy_image)

If you have a 3D matrix, the number of columns reported by size will be y = size(noisy_image,2)*size(noisy_image,3);. As such, when you are iterating through each pixel in your image, in column major order each plane would be placed side by side each other. What you should do is either convert your image into grayscale from RGB or filter each plane separately.

Also, you have an unnecessary casting performed in the loop. Just do it once outside of the loop.

Option #1 - Filter per plane

function [filtr_image] = avgFilter(noisy_image)
[x,y,z] = size(noisy_image);
filtr_image = zeros(x,y,z,'uint8');
for a = 1 : z
    for i = 2:x-1
        for j =2:y-1
            sum = 0;
            for k = i-1:i+1
                for l = j-1:j+1
                    sum = sum+noisy_image(k,l,a);
                end
            end
            filtr_image(i,j,a) = sum/9.0;
        end
    end
 end
end

Then you'd call it by:

filtr_image = avgFilter(noisy_image);

Option #2 - Convert to grayscale

filtr_image = avgFilter(rgb2gray(noisy_image));

Minor Note

You are using sum as a variable. sum is an actual function in MATLAB and you would be overshadowing this function with your variable. This will have unintended consequences if you have other functions that rely on sum later down the line.

Upvotes: 4

Dan
Dan

Reputation: 45741

I can't see why your code would repeat the image (unless it's a pattern cause by an integer overflow :/ ) but here are some suggestions:

if you want to use loops, at least drop the inner loops:

[x,y] = size(noisy_image);
filtr_image = zeros(x,y);
for i = 2:x-1
    for j =2:y-1
        % // you could do this in 1 line if you use mean2(...) instead
        sub = noisy_image(i-1:i+1, j-1:j+1);
        filtr_image = uint8(mean(sub(:))); 
    end
end

However do you know about convolution? Matlab has a built in function for this:

filter = ones(3)/9;
filtr_image = uint8(conv2(noisy_image, filter, 'same'));

Upvotes: 1

Related Questions