% dip05_3.m           gr09mar15
% Linear lowpass filters
clear all;
return
%%
f = double(imread('.\img\lena.tif'));
f = f(80:370,10:300);
[m,n] = size(f);

 f = zeros(m,n)+128;

fn = zeros(m,n,10);
for i=1:10
    noise = randn(m,n)*30;
    var(noise(:))
    fn(:,:,i) = f + noise;
    end;

g = sum(fn,3)/10;       % average of a "sequence" of images
 var(g(:))                   % noise variance drops by a factor of 10
                                % (to be measured on uniform image!)
figure(1);  imshow([f, fn(:,:,7), g],[0 255]); 

%%
f1 = (imread('.\img\clip10.tif'));  % average of an actual sequence of images
imshow(f1);  pause;
g = double(rgb2gray(f1));
g = g(80:370,10:300);
for i=1:9
    nam = strcat('.\img\clip0',int2str(i),'.tif');
    f1 = (imread(nam));
    f1 = double(rgb2gray(f1));
    f1 = f1(80:370,10:300);
    g = g + f1;
    end;
g = g /10;
% imwrite(g/255,'.\img\Clip_bw_av.tif');
imshow([f1 g],[]);  pause;
imshow(log([f1 g]+60),[]);          % for better visualization


%% 
 help filter2;  help imfilter;       % both use conv2, but filter2 does zero-padding only
% both perform correlation rather than convolution by default. 
% Important for filters without central symmetry (rare)

%%
f = zeros(5,5); f(3,3)=1;  % impulse (shifted to image center)
h = [1 2 3; 4 5 6; 7 8 9];
g1 = imfilter(f,h,'same','corr')  % default
g2 = imfilter(f,h,'full','conv')
g3 = conv2(f,h)

%%
f = round(rand(5,5)*3);
h = [1 2 3; 4 5 6; 7 8 9];
g1 = imfilter(f,h,'same')  % default
g2 = imfilter(f,h,'full')   % [zero padding]  rows/cols 2:N-1 are same as above
g3 = imfilter(f,h,'full','replicate') % [replica padding]  rows/cols 3:N-2 are same
                                      % only these rows/cols are not sensitive to padding

%%
figure(1);
f = double(imread('.\img\lena.tif'));
f = ((f./255).^.7)*255;    % just to make it more visible
noise = randn(size(f))*30;
fn = f + noise;
w = [1 1 1; 1 1 1; 1 1 1] / 9;              % (repeated) averaging filter
dum = fn;
for i=1:30
   g = filter2(w,dum);
%    g = imfilter(dum,w,'replicate');    %  note different border effects
                                        %    between zero-padding and replication
   imshow([fn, g],[0 255]);  pause(.2);
   dum = g;
   end;

%%
weq = w;
for i=1:10                              %  equivalent filter mask (freq. response: later)
    weq = conv2(weq,w);
    mesh(weq); axis([0 20 0 20 0 .2]); pause();
    end;    

%%
figure(2);
w1 = ones(15,15);               %  larger averaging filter
w1 = w1 / sum(w1(:));
g1 = filter2(w1,fn);
imshow([fn, g, g1],[0 255]);

%%
f = double(imread('.\img\cameraman.tif'));
w = [0 0 2; 0 2 0; 2 0 0]/6;                                % anisotropic filter
dum = f;
for i=1:20
    g = filter2(w,dum);
    dum = g;
    end;
imshow([f, g],[0 255]);

return;

%%%%%%%%%%%%          nonlinear filters: more later



