Part 3: Median Filter - RGB Image

MATLAB CODE:

clear all

%READ THE RGB IMAGE
I = imread('peppers.png');

A = imnoise(I,'Salt & pepper',0.1);
figure,imshow(A);title('IMAGE WITH SALT AND PEPPER NOISE');


%DEFINE THE WINDOW SIZE MXN
M=3;
N=3;

%PAD THE MATRIX WITH ZEROS ON ALL SIDES
modifyA=padarray(A,[floor(M/2),floor(N/2)]);

B = zeros([size(A,1) size(A,2)]);
med_indx = round((M*N)/2); %MEDIAN INDEX
for i = 1:size(modifyA,1)-(M-1)
    for j = 1:size(modifyA,2)-(N-1)
       
       
        temp = modifyA(i:i+(M-1),j:j+(N-1),:);
        %RED,GREEN AND BLUE CHANNELS ARE TRAVERSED SEPARATELY
        for k = 1:3

          tmp = temp(:,:,k);
          B(i,j,k) = median(tmp(:));

        end
      
       
    end
end


%CONVERT THE IMAGE TO UINT8 FORMAT.
B = uint8(B);
figure,imshow(B);
title('IMAGE AFTER MEDIAN FILTERING');



EXPLANATION:
·        The image is read into the matrix I.  
·        Salt and pepper noise is added to the image.  Learn howto add 'salt and pepper noise to an image'.
·        Define the window size MxN example: 3x3, 7x7, 5x3
·        Pad the image with zeros on all sides. This is done to perform the filtering on the border pixels. Learn howto pad with zeros using MATLAB built_in function padarray.
·        Median is the middle point of the series. The index that is obtained by dividing the total number of elements in a window by 2 gives the position.

·        A sliding window of size M x N is used on each channel (Red, Green and Blue) separately and the elements in the window are sorted and the middle element from the sorted array is chosen.

No comments:

Post a Comment