version 1.0.0.0 (1.59 KB) by
Jose Vicente Manjon-Herrera

Application of kmeans clustering algorithm to segment a grey scale image on diferent classes.

This program gets an image and the desidered number of partitions and finds the means of the different classes and provides a clasified image

(mask).

Jose Vicente Manjon-Herrera (2021). kmeans image segmentation (https://www.mathworks.com/matlabcentral/fileexchange/8379-kmeans-image-segmentation), MATLAB Central File Exchange. Retrieved .

Created with
R13SP1

Compatible with any release

**Inspired:**
TACTICS Toolbox

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!Create scripts with code, output, and formatted text in a single executable document.

aswin nambiarError in kmeans1 (line 58)

hc(ind(i))=cc(1);

please help me to correct this error

tashu Dabariyafunction [mu,mask]=kmeans(ima,k)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%

% kmeans image segmentation

%

% Input:

% ima: grey color image

% k: Number of classes

% Output:

% mu: vector of class means

% mask: clasification image mask

%

% Author: Jose Vicente Manjon Herrera

% Email: jmanjon@fis.upv.es

% Date: 27-08-2005

%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

ima=imread('1.jpg');

ima=rgb2gray(ima);

subplot(2,2,1),imshow(ima);

k=2; %Number of classes

[~,mask]=kmeans(ima,k);

mask=mat2gray(mask);% convert matrix to image

subplot(2,2,2),imshow(mask);

% check image

ima=double(ima);

copy=ima; % make a copy

% greyLevels=2^8-1; % Number of gray levels

ima=round(ima);

ima=ima(:); % vectorize ima

mi=min(ima); % deal with negative

ima=ima-mi+1; % and zero values

s=length(ima);

% create image histogram

m=max(ima)+1;

h=zeros(1,m);

hc=zeros(1,m);

for i=1:s

if(ima(i)>0)

h(ima(i))=h(ima(i))+1;

end

end

ind=find(h);

hl=length(ind);

% initiate centroids

k=str2double(k);

mu=(1:k)*m/(k+1);

% start process

while(true)

oldmu=mu;

% current classification

for i=1:hl

c=abs(ind(i)-mu);

cc=find(c==min(c));

hc(ind(i))=cc(1);

end

%recalculation of means

for i=1:k

a=find(hc==i);

mu(i)=sum(a.*h(a))/sum(h(a));

end

for i=1:k

if(isnan(mu(i)))

mu(i) = i*m/(k+1);

end

if(mu==oldmu)

break;

end

end

% calculate mask

s=size(copy);

mask=zeros(s);

for i=1:s(1)

for j=1:s(2)

c=abs(copy(i,j)-mi-mu);

a=find(c==min(c));

mask(i,j)=a(1);

end

end

mu=mu+mi-1; % recover real range

end

I got an error and i am trying to use this code as a greenness identification but I don't get any segmented image help me to solve error

Index exceeds the number of array elements (0).

Error in kmeans (line 58)

hc(ind(i))=cc(1);

Kartikeya DixitNhat Nguyen Thanh MinhThank you

moom h%% to display result

ima=imread('ims1.jpg');

ima=rgb2gray(ima);

subplot(2,2,1),imshow(ima);

k=2; %Number of classes

[mu,mask]=kmeans(ima,k);

mask=mat2gray(mask);% convert matrix to image

subplot(2,2,2),imshow(mask);

VeronikaI defined k before running the code and put ima=round(ima); before line 32, but still any output, MATLAB is still "busy".

AggiesI am a beginner and I am confused how should I interpret the outputs (numbers), is it possible to visualise it on the input image? anyone?

Waqas Ahmadbefreo running the code one has to define k i.e. the number of clusters, put ima=round(ima); somewhere before line 32 to round the m value and define a proper image to load

Vaishnuvi VWhy no output displayed? How to write code for it along with this current code?

nirmalaHello, I'm getting this error while running code

Error using kmeans (line 20)

Not enough input arguments

plz help me .how to see the segmented image

ziggyHi, does anyone know what type of distance measure is being used in this version of k-means?

I see the

c=abs(ind(i)-mu);

within the "current classification" part, is that Manhattan distance?

Also, is

mu=(1:k)*m/(k+1);

the standard way of calculating the centroids? I cannot seem to find a corresponding formula.

Thanks!

rahul vermaThis code is running fine, without o/p :-(

but i tried

imshow(mask,[])

imshow(mask)

i didn't get any output.

How to get the segmented image?

Karla Palmakhadija azharhow can i see the files??

wei lijaveria aminwhen i run matlab code to test this segmentation code, i have error sounds like this "Input argument "k" is undefined.How can i define k?"plz help me

javeria aminwhen i run matlab code to test this segmentation code, i have error sounds like this "Input argument "k" is undefined."

Bariqi AbdillahWhen I run the matlab code with my .jpg image nothing happens. I tried "imshow(mask)" but I only get a white image. What am I doing wrong ? Is there something to add to the code to get an image output with the result of the segmentation on my image ?

Srinivasan Ramandoes it return the k centroids from the kmeans clustering as classes?

Lipismita Panigrahiplease help me to see the output.

Sarada kadiyamcan u tell how to see this output.Am getting problem while running code..please help me please thanks in advance

Qianwhy i cant see the code?

AZamaPlease could anyone tell me how this code works?

Thanks in advance.

Vasumathi GaneshHello sir, I'm getting this error while running your code

Error using kmeans (line 20)

Not enough input arguments.

NunoHow can i define k?

TusharHow to get the segmented image?

marjanfatmahello,i am realy poor in matlab coding and i dont know how to overcome it.Kmeans in image processing is my homework,too.Still i dont know how i must progress in this:S Please help me

Mark ToolanAswin Raj:

Try 'k=str2double(k);' just before line 46

Aswin Rajkmeans

Error using kmeans (line 46)

Not enough input arguments.

L46 : mu=(1:k)*m/(k+1);

how to overcome this error??

naipunya pradhanWhen I run the matlab code with my .jpg image nothing happens. I tried "imshow(mask)" but I only get a white image. What am I doing wrong ? Is there something to add to the code to get an image output with the result of the segmentation on my image ?

MariaOh, I may have missed something, but I may be worth adding a line of say:

ima=round(ima)

on line 33 before the first loop in case you have a matrix of non-integer values.

thanks

MariaNice, simple, elegant. Cheers.

sahar Pordeli BehrouzMoe MyintWhen I run the matlab code,i have error sounds like this "Input argument "k" is undefined."

in line 42...

pls help me....

Thanks a lot....

nandinii should apply kmeans for the background eliminated image please help me

quixWhy not show users how to visualize the result?

hung huujiyoJessica please use imshow(mask,[]) and check. It should work

JessicaWhen I run the matlab code with my .jpg image nothing happens. I tried "imshow(mask)" but I only get a white image. What am I doing wrong ? Is there something to add to the code to get an image output with the result of the segmentation on my image ?

sukhvir kaurwhen i run this code then output of mask is red...why this is happening can anyone help me plz???

shazwani kamarudinwhen i run matlab code to test this segmentation code, i have error sounds like this "Input argument "k" is undefined."

in line 42...

help me please

mangood UKwhere is the segmentation image result??

Raz ShimoniThank you.

JavierExcellent!

Souravhow do i get to see the code?

parvathi menonHow do I implement this code?

Nikolay S.Works nicely.

A little word of advice, if I may...

By adding the following two lines (in lines 25-26) you will be capable of dealing non integer inputs also (matrix of double's in my case):

Consider performing rgb2gray to deal with color image inputs as well.

greyLevels=2^8-1; % Number of gray levels

ima=round(greyLevels*ima/max(ima));

Best regards, and keep the good work!

Neha@zheng~~~ plzz help if u r able to understand the code..

zhengvery good

zhengvery good

Nehawhere is the statement for loading image by using this code..?? :(

Nehaplzz help me how to implement it... i need k-mean clustering deadly for my project work having deadline 15July...

3omyer 3omayerExcellent code, but please, I need to extract the pixels for each classes to calculating some statistical proprities, like mean or std. can you help me please !!

NidhiHow will we recover the image from the

matrix??

NidhiCan anyone help me in how to implement this function on image ??

zhou joinrubbish

Aksam IftikharExcellent code, but I came across a problem in this code. Whenever number of clusters specified are more than possible partitions of the image the algorithm got stuck. Here is the solution.

find following line in the given code

if(mu==oldmu) break;end;

now add following lines of code before this line.

for i=1:k,

if(isnan(mu(i)))

mu(i) = i*m/(k+1);

end

end

The problem was occuring when NaN was encountered in centroid computation.

lbrcexddfd

VipulSalehThe segmented image should be multi colors, based on number of clusters. But I have mask with only one color "always red", Why? I need the segmented image

Help me please...

David SmithDoesn't work for me. Tried to run it on the Shepp-Logan phantom:

>> [u,m]=kmeans(phantom(128),4);

??? Attempted to access h(1.2); index must be a positive integer or logical.

Error in ==> kmeans at 35

if(ima(i)>0) h(ima(i))=h(ima(i))+1;end;

David Smithops OPSi don't how its work with image !! do u have GUI ?

Ahmedosunmbs unduoVinkle kumargood one..

AnnaCan you pls tell me for which k=? did you obtain the result from the image?

Ömer KAYAthere is a problem if there is a total range of grey levels in the image then it is going to be a kind of problem with the solution.

The ımage is complete white?

What shall we do/do not about it?

Nice code...

Rekha G Rsannymahmoud can yo send me the right code?

spectral>Mahmoud Shehadeh I'm gonna send you an email.

k..tq..does it works on the grayscale image..

Mahmoud ShehadehI'm gonna send you an email.

spectral'Mahmoud'..do you have the corrected code

Mahmoud Shehadehsorry that was not the right code :)

spectralanyone can help me..why i didn't successfully execute the results..

i'm using the jpeg image.tq

Mahmoud ShehadehNitinLiu Zhidangood

Seena Ghazitrabajo bién

AirballmanWorks fine, thanks!

A bit long when used on high resolution images. But I guess it comes from the kmeans methods itself :)

TRAN VietDungnice !

BhanuPlease tell how to execute this code

BhanuPlease help me how to execute this code in matlab

Aditya GuptaThanks, works good.

Tai FeiDank!

Assaf ZaritskySmall bug at line#73, should be:

c=abs(copy(i,j)-mi-mu);

instead of:

c=abs(copy(i,j)-mu); % (mi missing)

Also, performance can be quite improved

hbu it is very beauteful,excellent!

ASHWINI SAPKALI want to apply kmeans for landsat images pls help me for dat

kiruba maniim doing my final year project in image segmentation based on MRF with ANT COLONY SYSTEM,i dont have any idea ab't that,can u help me,my first module is k-means,can u explain k-mans in depth.

Patirniche DinuAbirami Balasubramaniyangood

mcasarah tuckerfd fdafdgood

Ghassan alyamiChris Yangplease help me, how to use this code

Gustavo MeschinoVery fast implementation!

It would be great if it is improved to enter more than one input image.

Adrian Lópezmanoj kumarhelpful

Santhosh KumarI need a help from u to solve a paper in image processing

AYEB YAKOUBthis function works only for integer values of gray level, not for double

smiled fisherVolker E.Yurniar SupanggiGood work, this code very useful for me, but I need method hierarchical clustering for image..., Any idea for me?

John Thebridgeoscar foreroMikel Rodriguez (www.cs.ucf.edu/~mikel)No errors, well done. For some applications you might want to use Jose Vicente Manjon-Herrera's EM image segmentation implementation though.

Elena Cherworkes good

mohammad sadeghzadehMilind PotdarRaj Pai Panandikercool coolleeni m doing my final year project of mini portions segmentation method in face recognition using matlab. may i know how to put my cropped small portions of the face into matrix (eg: 6x9 matrix, where 6 refer to number of photos, n 9 refer to the number of small portions). by the way, i also would like to know how can i compare the matrix column by column in order to get the eigenvalues. n i m new to matlab, so i hope u will help me to clear my doubts. if u have to source code, pls send a copy to me. thanks and really appreciate for your help. Hope can hear from u soon.

kosala jayakodyDavor ConejoJust Perfect. Very fast and great code.

Jean-Paul KoumaVery good and fast!

Xin HuangK-means is a classic un-supervised classification algorithm. In your code, is there new ideas about k-means? And can you compare the k-means,ISODATA,SOM mathods?

Stanley ZietzExcellent. Works well.

Bashar NusirRamir SokurkaExcellent!