MATLAB: How to remove Randomness in Cluster formation in kmeans clustering method? How to debug the error “Empty Cluster Created” which occurs at random

disease detectionkmeansleafleaf disease detection

We are working on a project to detect plant diseases using Matlab image processing toolbox. Initially we resize and adjust the contrast of the leaf image; then apply kmeans clustering. The yellow spots, brown spots and green part need to in separate clusters. The clusters are formed randomly. We have written a code to identify the clusters. But, sometimes the green and yellow spots/ yellow and brown spots appear in the same cluster. Also, at times we get an error "Empty Cluster created". Sometimes on running the prog twice/thrice, the error doesn't show. We are not understanding where/what the problem is. Please help us ..
The code is as under:
clear all;
close all;
% Reading and displaying image %
I = imread('leaf-572x600.jpg');
figure,subplot(3,3,1),imshow(I),title('Original Image');
% Creating color transformation from sRGB to L*a*b %
cform = makecform('srgb2lab');
% Applying above color transform to the sRGB image %
lab_I = applycform(I,cform);
% Converting into double %
ab = double(lab_I(:,:,2:3));
% obtaining rows and columns of transformed image %
nrows = size(ab,1);
ncols = size(ab,2);
% Reshaping image taking each value column wise %
ab = reshape(ab,nrows*ncols,2);
% No of clusters to be created with five iterations %
nColors =5;
[cluster_idx cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean','start','uniform');
% Reshaping and showing the clusters
pixel_labels = reshape(cluster_idx,nrows,ncols);
subplot(3,3,2),imshow(pixel_labels,[]), title('Image labeled by cluster index');
% creating five element array %
segmented_images = cell(5);
% Creating tiles for three different colors %
rgb_label = repmat(pixel_labels,[1 1 3]);
% Assigning clustered objects to array(segmented_image) %
for k = 1:nColors
color = I;
color(rgb_label ~= k) = 0;
segmented_images{k} = color;
end
% displaying different cluster objects %
subplot(3,3,3),imshow(segmented_images{1}), title('Cluster 1');
subplot(3,3,4),imshow(segmented_images{2}), title('Cluster 2');
subplot(3,3,5),imshow(segmented_images{3}), title('Cluster 3');
subplot(3,3,6),imshow(segmented_images{4}), title('Cluster 4');
subplot(3,3,7),imshow(segmented_images{5}), title('Cluster 5');

Best Answer

To remove the randomness, instead of passing 'uniform' for the 'start' option, pass a matrix of fixed initial centroids.
To get rid of the empty cluster message, add an 'emptyaction' option with either 'drop' or 'singleton' as the value. I will leave it to others to describe the reason that empty clusters get formed at all.
Related Question