finalimage = zeros(240, 320);
for i=1:200
    finalimage = plus(finalimage, ag(:, :, i));
end
bgfinal = finalimage ./ 200;
for j=1:200
    agnew(:, :, j) = minus(ag(:, :, j), bgfinal);
end
imtoshow = zeros(240, 320);
for k=1:200
    imtoshow = plus(imtoshow, agnew(:, :, k));
end
imgtoshow = imtoshow ./ 200;
bgfinal1 = plus(imgtoshow, bgfinal);
PIM = padarray(bgfinal,[2,2],'replicate');
%PIM = padarray(bgfinal1,[2,2],'replicate');
% new size of input image
dim = size(PIM);

% start main loop for filtering
for m = (1+2):(dim(1,1)-2)
    for n = (1+2):(dim(1,2)-2)
        % parameters for filtering
        a = PIM(m,n);
        b1 = PIM(m,n+1);b2 = PIM(m,n+2);
        c1 = PIM(m-1,n+1);c2 = PIM(m-2,n+2);
        d1 = PIM(m-1,n);d2 = PIM(m-2,n);
        e1 = PIM(m-1,n-1);e2 = PIM(m-2,n-2);
        f1 = PIM(m,n-1);f2 = PIM(m,n-2);
        g1 = PIM(m+1,n-1);g2 = PIM(m+2,n-2);
        h1 = PIM(m+1,n);h2 = PIM(m+2,n);
        i1 = PIM(m+1,n+1);i2 = PIM(m+2,n+2);
        para1 = [a,b1,b2,d1,d2,f1,f2,h1,h2];
        para2 = [a,c1,c2,e1,e2,g1,g2,i1,i2];
        para3 = [a,median(para1),median(para2)];
        % output filtered image
        MIM(m-2,n-2) = median(para3);
    end
end
% filtered image by median filter for comparison
M = medfilt2(bgfinal,[5,5]);
figure
subplot(3,3,1)
imshow(bgfinal);
title('Background Image')
subplot(3,3,2)
imshow(bgfinal1);
title('Background Image With High Pass Filter')
subplot(3,3,4)
imshow(M);
title('Normal Median Filter')
subplot(3,3,5)
imshow(MIM);
title('Hybrid Median Filter')
subplot(3,3,7)
imshow(pic53);
title('Final Image: Description in Text')