MATLAB: Median Filter code problem:

filterimageMATLABnoise removal

Hello Dear Experts,
I am trying to build the median filter with given window size. Here is what I did so far, please correct me because for some reason I don't get the right results:
function [ newImg ] = myMedian( img, rows, cols )
ModifyImg = padarray(img,[1 1]);
for i = 1:(size(ModifyImg,1) - 2)
for j = 1:(size(ModifyImg,2) - 2)
window = zeros(rows,cols);
inc = 1;
for x = 1:rows
for y = 1:cols
window(inc) = ModifyImg(i + x - 1, j + y - 1);
inc = inc + 1;
end
end
Sorted_Window = sort(window);
newImg(i,j) = Sorted_Window(ceil(0.5*rows*cols));
end
end
end

Best Answer

Try something like this (untested):
function [ newImg ] = myMedian( img, rows, cols )
ModifyImg = padarray(img,[1 1]);
for i = 1:(size(ModifyImg,1) - 2)
for j = 1:(size(ModifyImg,2) - 2)
window = ModifyImg(i:i+rows-1, j:j+cols-1);
Sorted_Window = sort(window(:));
newImg(i,j) = Sorted_Window(ceil(0.5*rows*cols));
end
end
By the way, if you want to see how it's done with blockproc, in jumps of 8 pixels, see this demo code:
% Demo code to divide the image up into 16 pixel by 16 pixel blocks
% and replace each pixel in the block by the median, mean, or standard
% deviation of all the gray levels of the pixels in the block.
clc;
clearvars;
close all;
workspace;
fontSize = 20;
% Change the current folder to the folder of this m-file.
if(~isdeployed)
cd(fileparts(which(mfilename)));
end
% Read in a standard MATLAB gray scale demo image.
folder = fullfile(matlabroot, '\toolbox\images\imdemos');
if ~exist(folder, 'dir')
% If that folder does not exist, don't use a folder
% and hope it can find the image on the search path.
folder = [];
end
baseFileName = 'cameraman.tif';
fullFileName = fullfile(folder, baseFileName);
grayImage = imread(fullFileName);
% Get the dimensions of the image. numberOfColorBands should be = 1.
[rows columns numberOfColorBands] = size(grayImage)
% Display the original gray scale image.
subplot(2, 2, 1);
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'Position', get(0,'Screensize'));
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
% Define the function that we will apply to each block.
% First in this demo we will take the median gray value in the block.
medianFilterFunction = @(x)median(x(:))*ones(size(x),class(x));
% Block process the image to replace every pixel in the
% 8 pixel by 8 pixel block by the median of the pixels in the block.
blockSize = [8 8];
blockyImage8 = blkproc(grayImage, blockSize, medianFilterFunction);
% Display the block median image.
subplot(2, 2, 2);
imshow(blockyImage8, []);
title('Block Median Image', 'FontSize', fontSize);