Monday, November 18, 2013

Write a program in MATLAB to generate a median of an image.

clc;
clear all;
close all;

A=imread('median.tif');
% Pad the matrix with zeros on all sides
modifyA=zeros(size(A)+2);
B=zeros(size(A));
% copy the original image matrix to the padded matrix
for x=1:size(A,1)
    for y=1:size(A,2)
        modifyA(x+1,y+1)=A(x,y);
    end
end
 
h = waitbar(0,'Calculating Median Operation please wait......');

% Let the window be an array store the 3-by-3 neighbour
% values in the array sort and find the middle element
     
for i= 1:size(modifyA,1)-2
    for j=1:size(modifyA,2)-2
        window=zeros(9,1);
        inc=1;
        for x=1:3
            for y=1:3
                window(inc,1)=modifyA(i+x-1,j+y-1);
                inc=inc+1;
            end
        end
        med=sort(window);
        % Place the median element in the output matrix
        B(i,j)=med(5);
    end
    waitbar(i/size(modifyA,1));
end
% Convert the output matrix to 0-255 range image type
B=uint8(B);
figure('Position',[100  100 1200 550]);
subplot(1,2,1),imshow(A),
ylabel('Image with salt-papper noise','Color','r','FontSize', 20,'FontAngle', 'italic');
subplot(1,2,2),imshow(B),
ylabel('Image after median filtering','Color','r','FontSize', 20,'FontAngle', 'italic');
close(h);

8 comments: