p = imread('pendulum.jpg');
pg =im2gray(p);

% help im2gray - convert a color image to grayscale
%
% The conversion formula is:
% 0.2989 * R + 0.5870 * G + 0.1140 * B
%  
% Or this one:
% 0.299 * R + 0.587 * G + 0.114 * B

gray = uint8(0.2989 * double(p(:,:,1)) + 0.5870 * double(p(:,:,2)) + 0.1140 * double(p(:,:,3)));
diff = abs(pg - gray);
figure; imshow(diff)
max(max(diff))  % print the maximum difference

res=edge(pg,'canny');
figure; imshow(pg)
figure; imshow(res)

% threshold parameter
res=edge(pg,'canny', 0.1);
figure; imshow(res)

% adjust the threshold parameter
res=edge(pg,'canny', 0.2);
figure; imshow(res) 

% call the matlab function 
res2=edge(pg,'sobel');  
figure; imshow(res2) 



%% Implement the Sobel Edge detection algorithm
Sx = [-1  0  1;
      -2  0  2;
      -1  0  1]

Sy = [-1 -2 -1;
       0  0  0;
       1  2  1]

% Some references use these instead
%
%Sx = [ 1  0  -1;
%       2  0  -2;
%       1  0  -1]
%
%Sy = [ 1  2  1;
%       0  0  0;
%      -1 -2 -1]
%             
% Note that Sy = Sx'


% Optionally, you can decide to smooth the image first
% pg=imfilter(pg, ones(3,3)/9);


threshold = 0.25  % possible values in [0, 1]
ex = imfilter( double(pg), Sx);
ey = imfilter( double(pg), Sy);

e = sqrt(ex.*ex + ey.*ey);
maximum = max(max(e));
e = e/maximum;

result = uint8((e > threshold) * 255);
figure; imshow(result)

% Matlab allows you to get the two intermediary results
% h =edge(pg,'sobel', 0.2, 'horizontal');
% v =edge(pg,'sobel', 0.2, 'vertical');
% b =edge(pg,'sobel', 0.2, 'both');


%% THIS ALSO WORKS
threshold = 200
ex2 = conv2(double(pg), Sx, 'same');
ey2 = conv2(double(pg), Sy, 'same');
e2 = sqrt(ex2.*ex2 + ey2.*ey2);
result2 = uint8((e2 > threshold) * 255);

figure; imshow(result2)

