close all
clear all

%-----------------------------------------------------------------------
% before running this function second time for the target image
% make sure you have saved the need full data, (the data of
% edge detection algorithm).
%------------------------------------------------------------------------

a=input('Enter the number of sementation desired : '); 
im=imread('ant.png');
[m,n,o]=size(im);
data=double(im);
datax=reshape(data,m*n,o);

% %Performing K-means operation
%in=kmeans(datax,a); // In-built matlab function

[in]=kmeans1(datax,a);

x = zeros(1, 3);
 % Calculating mean
 for i = 1:a
     j = find(in==i); %Finding index values for each value of i
     for k = 1:size(j, 1) %size will help in finding the row number 
         x(k,:)=datax(j(k),:);
     end
     temp(i,1)=mean(x(:,1));
     temp(i,2)=mean(x(:,2));
     temp(i,3)=mean(x(:,3)); 
end

% % Resstructuring the image
index=1;
for i=1:n    
    for j=1:m
        for k = 1:3
            result(j,i,:)=temp(in(index),:);
        end
        index=index+1;
    end
end
result=result;
new=uint8(result);  % generates colour image

new2=rgb2gray(new); % Converting segmented image into gray level image

%--------------------------------------------------------------------
%Depending upon the number of clusters, different algorithms for edge
%detection generates different results. Implementation of all the
%algorithms allows user to select the best suited result for the image
%matchin
%---------------------------------------------------------------------

%Edge Detection Algorithms

eg1=edge(new2,'sobel');
eg2=edge(new2,'prewitt');
eg3=edge(new2,'roberts');
eg4=edge(new2,'log');
eg5=edge(new2,'canny');
eg6=edge(new2,'zerocross');

% % image Contour
 [v1,v2]=imcontour(eg5,2,'k-');
 

% % Image Display
 figure; subplot(3,3,1), imshow(im);
         subplot(3,3,1), title('Original');
         subplot(3,3,2), imshow(new);
         subplot(3,3,2), title('Segmented');
         subplot(3,3,3), imshow(new2);
         subplot(3,3,3), title('Gray Level');
         subplot(3,3,4), imshow(eg1);
        subplot(3,3,4), title('sobel');
        subplot(3,3,5), imshow(eg2);
        subplot(3,3,5), title('prewitt');
        subplot(3,3,6), imshow(eg3);
        subplot(3,3,6), title('roberts');
        subplot(3,3,7), imshow(eg4);
        subplot(3,3,7),title('log');
        subplot(3,3,8), imshow(eg5);
        subplot(3,3,8),title('canny');
        subplot(3,3,9), imshow(eg6);
        subplot(3,3,9),title('zerocross');
% 
