s = [zeros(1,100), ones(1,100)];
figure(12); plot(s)
axis([0,200, -1,2]);
I = s + .2*randn(1,200);
figure(12); plot(I);
% I now contains a step edge with a lot of noise added to it.

D = [-.5 0 .5];
figure(12); plot(imfilter(I,D,'replicate'));
% If we take the derivative, we get something pretty noisy.

% figure(13); plot(I(1:198) - I(3:200))

sig = 2.5; a = -5:1:5; G = exp( (- a.^2)/ (2*sig*sig))/(sig*(sqrt(2*pi)));
G = G./sum(G);
figure(12); plot(G)


GI = imfilter(I,G,'replicate');
figure(12); plot(GI)

figure(12); plot(imfilter(GI,D))
%plot(GI(3:100) - GI(1:98))

% Convolution is associative.

D = [.5 0 -.5];
GD = imfilter(G,D,'conv', 'replicate');
figure(12); plot(GD);
GDI = imfilter(I, GD, 'conv', 'replicate');
figure(12); plot(GDI)
figure(13); plot(imfilter(GI, D, 'conv', 'replicate')); 

% Finding peaks

n = length(GDI);
PEAKS = [0, (abs(GDI(2:(n-1))) > abs(GDI(1:(n-2))) & abs(GDI(2:(n-1))) > abs(GDI(3:n))), 0];
figure(12); plot(PEAKS.*GDI)
figure(12); plot(abs(PEAKS.*GDI) > .075)
hold on
figure(12); plot(I,'r.-')
hold off

% Scale
s2 = [zeros(1,60), ones(1,10), zeros(1,60), ones(1,70)];
figure(12); plot(s2)
axis([0,200, -1,2])
I2 = s2 + .1*randn(1,200);
figure(12); plot(I2)

sig = 1; a = -20:1:20; G = exp( (- a.^2)/ (2*sig*sig))/(sig*(sqrt(2*pi)));
G = G./sum(G);
figure(13); plot(G)
figure(13); plot(imfilter(I2, imfilter(G, D, 'conv', 'replicate'), 'conv', 'replicate'));

sig = 5; a = -20:1:20; G = exp( (- a.^2)/ (2*sig*sig))/(sig*(sqrt(2*pi)));
G = G./sum(G);
figure(14); plot(G)
figure(14); plot(imfilter(I2, imfilter(G, D, 'conv', 'replicate'), 'conv', 'replicate'));

sig = 15; a = -40:1:40; G = exp( (- a.^2)/ (2*sig*sig))/(sig*(sqrt(2*pi)));
G = G./sum(G);
figure(15); plot(G)
figure(15); plot(imfilter(I2, imfilter(G, D, 'conv', 'replicate'), 'conv', 'replicate'));

% 2d edge detection

swanbw = imread('swanbw.jpg');

J = smooth_image(swanbw, 0);
figure(12); colormap gray; imagesc(J);
[Dx,Dy] = image_gradient(J);
figure(13); imagesc(Dx);
figure(13); imagesc(Dy);

figure(13); colormap gray; imagesc(gradient_magnitude_direction(Dx,Dy));

figure(14); colormap gray; imshow(edge(swanbw,'canny', [.3 .5], 2))

% Corners

I = 100*ones(200,200);
for i = 100:150 for j = 50:(150-2*(i-100)) I(i,j) = 150; end, end
I = I/255;
I = I+.01*randn(200,200);
figure(19); colormap(gray)
figure(19); imagesc(I)

G2 = fspecial('gauss', 7, 1.5);
Is = imfilter(I, G2);
figure(19); imagesc(Is)

figure(15); colormap(gray); imagesc(edge(I,'canny',[],1)); input('')
figure(15); imagesc(edge(I,'canny',[],2)); input('')
figure(15); imagesc(edge(I,'canny',[],5)); input('')
figure(15); imagesc(edge(I,'canny',[],8)); input('')

I = I+.01*randn(200,200);
figure(15); imagesc(I); input('')
figure(15); imagesc(edge(I,'canny',[],1)); input('')
figure(15); imagesc(edge(I,'canny',[],2)); input('')
figure(15); imagesc(edge(I,'canny',[],5)); input('')
figure(15); imagesc(edge(I,'canny',[],8)); input('')


