%%
clear
close all

% Load in a test image
img = im2double(imread('cameraman.tif'));

figure
imshow(img,'InitialMagnification','Fit','Border','Tight')

%% We can define a filter ourselves

% The 'ones' command will make a matrix populated with ones of the size
% that you give.  We can then multiply by 1/9 to make sure that the sum of
% the matrix is 1 to not adjust overall intensity.  This is a mean filter
filt1 = (1/9)*ones(3,3)

% We apply the filter with the imfilter command
imgFilt1 = imfilter(img,filt1,'replicate');

figure
imshow([img imgFilt1],'InitialMagnification','Fit','Border','Tight')

% We can also define filters using repmat.  Repmat will take whatever
% number, array or matrix in the first argument, and copy it into the size
% that you give on the second argument.
filt2 = repmat(1/25,[5 5])
imgFilt2 = imfilter(img,filt2,'replicate');

figure
imshow([img imgFilt1 imgFilt2],'InitialMagnification','Fit','Border','Tight')

% You can create any arbitrary matrix as a filter and apply it.
Filt3 = [9 5 -3; 3 3 5; 0.5 1 -9]
Filt3 = Filt3/sum(Filt3(:)); % Normalize to have a total sum of 1

imgFilt3 = imfilter(img,Filt3);
figure
imshow([img imgFilt3],[],'InitialMagnification','Fit','Border','Tight')

%% Median filters 
% We can add noise with imnoise
imgSP = imnoise(img,'Salt & pepper',.01);

figure
imshow([img imgSP],'InitialMagnification','Fit','Border','Tight')

% Medfilt asks for an image, and then a neigborhood size
imgFilt4 = medfilt2(imgSP,[3 3]);
imgFilt5 = medfilt2(imgSP,[7 7]);

figure
imshow([imgSP imgFilt4 imgFilt5],'InitialMagnification','Fit','Border','Tight')

