%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This function 'imageSegmentationUsingKMeans' performs image segmentation using clustering approach. The clustering algorithm used
% here is called 'K-means' where 'K' is the number of clusters. The 'mean' value of intensities of each cluster represents the 
% cluster's value. It makes use of the function 'kmeans1' that implements the K-means clustering algorithm.
%
% Programmer : Nilesh Ghubade (nileshg@temple.edu)
% Date : Feb 2003
% Advisor : Dr.Longin Jan Latecki (latecki@temple.edu )
% Course : CIS 750 (Spring 2003) --> Video Analysis and Video Mining.
% Assignment : Image segmentation using "K-means" clustering.
% Department : Computer and Information Science Department, Temple University, Philadelphia, PA-19122, USA
%
% Input arguments:-
% imageFileName = The input image to be segmented.
% noOfClusters = The number of clusters for segmentation.
%
% Output : -
% The output displays original image and the segmented image besides it.
%
% Example : -
% 1) imageSegmentationUsingKMeans('test.bmp',5)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function imageSegmentationUsingKMeans(imageFileName,noOfClusters)
img = imread(imageFileName);
pixelCount = 0;
for rowCount = 1:size(img,1)
    for colCount = 1:size(img,2)
        pixelCount = pixelCount + 1;
        pixelMat(pixelCount,:) = img(rowCount,colCount,:);
    end
end

[center,distance,label,tse] = kmeans1(double(pixelMat),noOfClusters);

meanIntsOfCluster = center;
% 
% for index = 1:noOfClusters
%     clusterIndex = find(label == index);
%     meanIntsOfCluster(index,:) = mean(pixelMat(clusterIndex,:));
% end

pixelCount = 0;
for rowCount = 1:size(img,1)
    for colCount = 1:size(img,2)
        pixelCount = pixelCount + 1;
        segmentedImg(rowCount,colCount,:) = meanIntsOfCluster(label(pixelCount),:);
    end
end

titleForSegImg = strcat('Segmented Image. Number of Clusters = ',int2str(noOfClusters));
subplot(1,2,1);imagesc(img);title('Original Image');
subplot(1,2,2);imagesc(uint8(segmentedImg));title(titleForSegImg);

save('distance.mat','distance');
save('label.mat','label');
save('tse.mat','tse');

return