MATLAB Answers

Amina Bhaika

color image segmentation bsed on kmeans and Lab color space

Asked by Amina Bhaika
on 11 Jun 2012

I have used the following code for segmenting a plant image containing predominantly yellow and green colors. It uses k-means in the L* a* b* color space.I basically want to extract the yellow parts of the image and then further process these extracted parts for feature analysis.But each time i run the code i get a different order of the clusters formed by k-means.On further analysis i found that the yellow regions were always returning a higher centroid value than the green regions.So i automated the selection of the required yellow cluster based on maximum centroid value.Can you please tell me the reason why yellow clusters always return higher centroid value than green clusters.

he = imread(TestImagePath);
Orig = he;
figure, imshow(Orig), title('Original Image');
cform = makecform('srgb2lab');
lab_he = applycform(he,cform);
ab = double(lab_he(:,:,2:3));
nrows = size(ab,1);
ncols = size(ab,2);
ab = reshape(ab,nrows*ncols,2);
nColors = 3;
% repeat the clustering 3 times to avoid local minima
[cluster_idx cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean', ...
pixel_labels = reshape(cluster_idx,nrows,ncols);
%figure, imshow(pixel_labels,[]), title('image labeled by cluster index');
segmented_images = cell(1,3);
rgb_label = repmat(pixel_labels,[1 1 3]);*BOLD TEXT*
for k = 1:nColors
    color = he;
    color(rgb_label ~= k) = 0;
    segmented_images{k} = color;
figure, imshow(segmented_images{1}), title('objects in cluster 1');
figure, imshow(segmented_images{2}), title('objects in cluster 2');
figure, imshow(segmented_images{3}), title('objects in cluster 3');
mean_cluster_value = mean(cluster_center,2);
[tmp, idx] = sort(mean_cluster_value);
YellowRustClusterNum = idx(3);


1 Answer

Answer by M@lik Ali
on 9 Jul 2012

I use this code but i get the error at ??? Error using ==> kmeans Too many input arguments.

Error in ==> Kmeans1 at 21 [cluster_idx cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean', ...

Can you please help me..

  1 Comment

Alvi Syahrin on 7 May 2013

Have you tried to make it like this?

[cluster_idx cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean','Replicates',3)                   

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi test

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!