function edgeIm = gradient_edge_V2(tempCrop)
%**************************************************************************
% This is a function to extract edge based on the gradient of input image.
% 1. Input 'tempCrop 'is the image.
%
% Created By: Kaichang CHENG, Jul 10,2019
%**************************************************************************
C=double(tempCrop);

B=zeros(size(C,1)-2,size(C,2)-2);
for i=1:size(C,1)-2
    for j=1:size(C,2)-2
        %Sobel mask for x-direction:
        Gx=((2*C(i+2,j+1)+C(i+2,j)+C(i+2,j+2))-(2*C(i,j+1)+C(i,j)+C(i,j+2)));
        %Sobel mask for y-direction:
        Gy=((2*C(i+1,j+2)+C(i,j+2)+C(i+2,j+2))-(2*C(i+1,j)+C(i,j)+C(i+2,j)));
        
        %The gradient of the image
        %B(i,j)=abs(Gx)+abs(Gy);
        B(i,j)=sqrt(Gx.^2+Gy.^2);
        
    end
end
temp1 = uint8(255 * mat2gray(B));
temp2 = imsegkmeans(temp1, 2);% Based on the gradient image
% The area with bigger gradient value is target (smaller area). How to choose ?
one=length(find(temp2 == 1));
two=length(find(temp2 == 2));
if one<two
    temp2(temp2 == 1) = 1;
    temp2(temp2 == 2) = 0;
else
    temp2(temp2 == 1) = 0;
    temp2(temp2 == 2) = 1;
end
edgeIm = logical(temp2);
end
