File Exchange

image thumbnail

Adaptive kmeans Clustering for Color and Gray Image.

version (2.54 KB) by ankit dixit
Automatically cluster a Color or Gray image. No need for specify number of cluster.


Updated 29 Apr 2014

View Version History

View License

This algorithm is a fully automatic way to cluster an input Color or gray image using kmeans principle, but here you do not need to specify number of clusters or any initial seed value to start iteration, this algorithm automatically finds number of cluster and cluster center iteratively. It is a very fast implementation of clustering an image without knowing number of clusters.
1. Cluster a Gray(single channel(0-255)) or Color image(3 channel(0-255)) as in kmeans.
2. Not need to be specify number of cluster for clustering.
3. Very Fast implementation.
4. Very Easy to understand.
5. Easy to Modify the code according to your requirements.
6. No use of any Image Processing Tool Function.
This code uses same principle as in kmeans, but here you do not need to define number of clusters.

You can use this code to estimate the number of clusters(colors) present in image, this code may not be segment all images as you want, so post processing of clustered image is suggested.

Please review it after download, I am waiting for your suggestions and modifications.

Thank You,
Ankit Dixit

Cite As

ankit dixit (2020). Adaptive kmeans Clustering for Color and Gray Image. (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (106)


mariena aloor

Respected Mam
I'm using your algorithm for color image segmentation, but function always return GrayScale image. How to make result is RGB ? please send me the steps to my mail id:

mariena aloor

Respected Mam
This is a great work mam. algorithm is so good for my dataset i think. How you select 10 and 25 please explain mam.Mam shall i send my dataset .please you can work on my data and give me the output my mailid is :


priyatosh pradhan

ankit dixit

@Sreepriya, these are the default values you can change it according to your application, distth is basically bandwidth of a cluster which eventually helps to decide size of a cluster. I have chose maximum 10 iteration to run the code, because most of the data sets easily converged around 8-10 iterations; you can modify that too.

ankit dixit

@Braiki; you can use MATLAB's reshape function for the same; you need to specify shape parameters similar to input image shape.

ankit dixit

@Sapna and @Dippu ; I have not use any specific paper for this method; this algorithm is based on hierarchical clustering, you can google it for more understanding. Thank You.

Sreepriya Jeejesh

Hi Ankit,
I had gone through your code, but i have some doubts regarding this.
1. How you selected the "distth" value as 25?
2. if seed == newseed || j>10
if isempty(array) || i>10
How you selected above mentioned value 10?
It would be great if you can clarify these points.

Braiki Marwa

Hi Ankit...Good work. How can I reshape it and view it as an image?

Sreepriya Jeejesh

Hi Ankit, when I enter your code I got an error “ undefined function or method for input arguments of type uint8”

Sapna S

Hi Ankit...Good work. Could you please specify the paper you used as reference?

ravi m

dippu prakash

Hello @ankit ,
May i know what is the paper you used for reference.


Anyone helps please? Can I display the output image?

ankit dixit

@Beena Bethel, lb in the output argument is the clustered image only, you can reshape it and view it as an image.

Gilberto HM

Thanks, it is working very well. Just one question, what should be changed in the code to make work with multidimensional clustering? That means, we treat the column as one point...?

Beena Bethel

Good that we are getting the lb and centers. Can we view the clustered image?
Please clarify....


Why output of K_Means is a binary image??

Sradha Viswanath

when I go for clustering of gray scale images zi am getting 4 clluster points.I just need two clusters.Can anyone help me sort out this??

su mon aung

how to display the result image for different cluster number?

Vasundhara Acharya

Kent Yeap

For those who obtained just white images, please remember to add [] into your imshow() command.

Eg: imshow(lb,[]);

shivangi b

sir please tell me how to detect only tumor part with masking or morphology. My input image is color but after running code image is in the grayimage.To solve that i have used gray to rgb fuction files . so my my image is size and class are matching .now im having problems with parameters such as PSNR is -34.39, entropy 0.846, 4 correlation values . actually PSNR ENTROPY shold be high .


which paper have you used to implement this code?

leila belkhodja

can you help me please i tried this code on mammograms and i obtained WHITE images where is the problem

shanmuga priya

if i run
Error in ==> adaptcluster_kmeans at 17
if size(im,3)>1
the code i am getting error.
pls say how to run this code , i am new to matlab

ankit dixit

@ Kausu this algorithm have not written for exact segmentation of any image object, because it is not an application based technique, the best use of this algorithm is to approximate number of clusters in an image, once you done clustering than you have to apply some rules to get exact area in the image. Thank You


Hello Sir,

I have tried your code for segmentation of optic disk.But I didn't get accurate Optic disk from fundus image.

pooja pardeshi

can anybody help me to getting exact output. What commands i should hv to pass?

Ratna Saha

Hi Ankit,
I have tried your code for segmentation of nucleus. Its giving good result. But I couldn't find any reference either in the code or in any comments here. Can you please provide the reference that you have implemented in this code? Your answer will help me to better understand the code and better use of it.
Ratna Saha

Lam Nguyen

How do you calculate the distth and intercluster ( based on what criteria)?

Mohamed Abdalla

Is there any way to make k value as an input parameter?
Thank you

smitha ural

This code seems like threshold based clustering rather than adaptive k means clustering. Correct me if I am wrong.
The source for both algorithms I referred this paper -

smitha ural

Hi Ankit,
Can you please give the reference for this code ???
Any journals which will help in understanding the automatic selection of k ?


hi ankit,

i was trying to use this code for gray scale images and it is giving two errors
1. undefined function for uint8 type
2.function [lb,center] = GrayClustering(im)
Error: Function definitions are not permitted in this context.

I am using Matlab 2013 kindly help me out with this since it is very much important for my project.

i hope u will reply ASAP

Luu Thanh

Hello Sir, I'm using your algorithm, input images is RGB but function always return GrayScale with any cluster image. How to make result is RGB ?
[clusterimage, clustercenter] = adaptcluster_kmeans(f);
figure,imshow(clusterimage==6,[]) % all image return grayscale
Thank !

ankit dixit

@ashwati, can you send me your test images along with the results, so i can have proper understanding about your problem, Thank You

Ashwati Menon

Hi ankit,thankyou so much for the code.The code is not showing any errors while running but the output figure displayed has just a small white line showing in the middle, be it for any input image. We are inputting a grayscale image. Could you please help out in this case and suggest what can show the segmented output image.

Shaveta Arora

Stephan Koehler

Vishal Vende

Undefined function 'ColorClustering' for input arguments of type 'uint8'.

Error in adaptcluster_kmeans1 (line 21)
[lb,center] = ColorClustering(im); % Check Image is Gray or not.

what should i do remove these error...

tan yuki

Hi ankit.

Thanks for your fast response. Can I know how and what kind of mask should be create? and I am confused for the example that you gave of binary image=label image==cluster number.

I am kinda new in this Matlab programming and very thanks for your patient. ^^

ankit dixit

@tan, yes you can get original image as segmented image, for this you have to use label matrix as a Mask create a binary image for corresponding label(for e.g. bw = labelim == cluster_number)and use this image as mask to fetch values from your original image, just multiply this mask to your original image(segIm = image.*double(bw)), your segIm will be segmented image.

Thank You

tan yuki

Hi ankit dixit

I have display the output image of lb and center which is in array form to see the effect of the result but is there any ways to display the image as the original image to compare the difference? For example if I am want to segment a cell image, is it possible to show the same image but with region of background, cytoplasm and nucleus by using this clustering algorithm?

Your reply is very much appreciated.

narayana reddy

I and my team is doing project on skin cancer detection using image processing we done median filtering operation but we are facing problem with segmentation of skin lesion image
will any body help us

narayana reddy

how to download the matlab code for this algorithm

Sayan Datta

I was having a little trouble displaying the clustered image. But the comments helped me out.
Thanks this works great!


This works very well, good job !

I was wondering if you could refer me to the paper/algorithm which you implemented.

Thank you

Gautam Kumar

hey..i got output, everything is OK with algorithm. thank you

Gautam Kumar

i am getting an error:
Error using adaptcluster_kmeans (line 16)
Not enough input arguments.
Error in run (line 64)
evalin('caller', [script ';']);

can anyone help me please....? or suggest me the steps to run this .m file.

ankit dixit

@Jack, In Lab color space L represents intensity image, a and b are representation of colors on different axes, now if you want to cluster an Lab image, you should cluster only a and b images, because there is no direct relation between L and other two components, here L, a and b components are not like r,g and b. and I think this code is not written for clustering of a two channel image Thank you.


The Algorithms works really good on RGB images and gray scaled images but does not work well at all on LAB images (images in Lab color space).

Is there a way for me to apply your algorithm on LAB images ?

Mohamed Dahmani

parvathy u s

Sir. i already input the image, but i'am getting a white screen as output,and also i want to see the clusters output also.could u please help me sir

sourabh r

I'm trying to segment an image of the moon to detect hazards using your code,but not able to get accurate clusters plz can u tell me hw to modify this code.


first i want to thank you for great code and second i want your help in saving clustered image to my local pc and specify the number of clusteres

Vasumathi Ganesh

Sir how to run this file?

hanna zainal

sir i already input the image, but im getting problems on visualizing the clusters. could u help me pls


X Liu

if you want to cluster spatial point, just use the matrix as an input. However, as the algorithm use the mean value of the matrix as the initial seed and use the distance between each point to the seed, it may not generate the desired clustering as what you want. You may give it a try and see how it goes.


Hi ankit dixit,

I need to cluster spatial point with coordinate X,Y, can you provide me some explanation about the input? I have not an array but a matrix of N rows (number of points) and 2 columns (X valueand Y value).

Thanks in advance


Thanks for the quick response...

ankit dixit

@ Nisha, output image of clustering algorithm always a labelled image, where label of a pixel defines cluster number of that pixel, in this function two outputs are generated clustered image and cluster center, to visualize cluster image you have to put full range show argument in "imshow" function. for e.g.
figure, imshow(clusteredImage,[ ])
above line will show the clustered image.


Thank you for explaination....
Presently I'm struggling with the value of "lb" as output...
The lb output is in form 1 1 1 2 2 1 3,etc,, but instead I think it must be image pixel values as output... I tried to find "lb" values but I think they r cluster numbers, if yes! then how image got plot in output?.....
Please help me out......

ankit dixit

Hello manu,

I have checked the code and run it on my machine, i am not getting any error in execution of code, i dont know why you guys are getting errors. and there is nothing in those line which can show any kind of errors.

have you made any kind of changes in the code like, try to change any statement due to warning kind of thing? if so, dont make any changes, just run the code with the defaults and see whether its giving any error or not.


Hi ankit..
Its a great piece of work....really helpful.
I tried using your code but getting error:
??? Error: File: adaptcluster_kmeans.m Line: 72 Column: 3
Expression or statement is incorrect--possibly unbalanced (, {, or [.
can you suggest the solutions for this
lines 70 -72 are

distance = ((vector-centers).^2);% Find distance between center and pixel value.
[~,lb] = min(distance,2);% Choose cluster index of minimum distance.
lb = reshape(lb,size(gray));% Reshape the labelled index vector.

ankit dixit

@Dipali and @pradhan, I have tested the code but not getting any kind of error and most important thing there is no function have been used which may be version dependent, because its a algebra kind of implementation, try to check any bracket or parenthesis is misplaced or not. or write me the specific line in which this error is occurring.
Thank You

Dipali Murudkar

I am using Matlab 7.8. Will your code work or I have to recode somethings?
I get an error when I run it on a gray image:
??? Error: File: adaptcluster_kmeans.m Line:
72 Column: 3
Expression or statement is
incorrect--possibly unbalanced (, {, or [.

Please suggest modifications.

naipunya pradhan

I am using Matlab 7.8. Will your code work or I have to recode somethings?
I get an error when I run it on a gray image:
??? Error: File: adaptcluster_kmeans.m Line:
72 Column: 3
Expression or statement is
incorrect--possibly unbalanced (, {, or [.

Please suggest modifications.

Gopalakrishnan M

@ ankit dixit, i have seen few comments and tried to run the program finally i got the cluster center result along with the error message Please help me:

function [lb,center] = adaptcluster_kmeans(im)
Error: Function definitions are not permitted in this context.

Gopalakrishnan M

Hi @ ankit dixit, i am new to matlab, i dont know how to run your program can u please help?

ankit dixit

@ Nisha, this is a binary clusetering algorithm, where you cluster a data set by hierarchical clustering, choose one seed value in my case it is mean value of data, than divide data in two cluster on the basis of defined distance (in this case it is std var of data) than check convergence, do this process in iterative manner until convergence of algorithm.

Thank You

ankit dixit

@ rizwan, to execute the algorithm you just have to give input image (gray or color) to the function. and it will return 2 output arguments 1 is the clustered image and another contains cluster centers.

[clusterimage,clustercenter] = adaptcluster_kmeans(image);


hi Ankit..
Thanks for the program. It is really helpful for clustering.
I was wondering if you could plz provide me the algorithm...


Hi Ankit,

Thanks for this effort. Can you please write some simple line of code showing how to run this code. Please explain with simplicity as i am new to matlab.

Ghulam Rasool


Ankit, please provide us the research paper where you illustrated this algorithm : adaptive k means . Thank U

ankit dixit

@masitah, clustering is depends totally on your input image properties, try with some different images and see the result, if problem remain same, then try to adjust distance variable in function. also when showing cluster image make sure you are showing image for full range e.g. imshow(image,[]). Thank you

masitah abdul lateh

hi, i need your help.when i run this code, only certain pixels of the image are clustered. while other pixels returned white.. why?


Hi Ankit,

I tried the algorithm but this error message came up:
'Error using adaptcluster_mod (line 16)
Not enough input arguments.

function [lb,center] = adaptcluster_kmeans(im)
Error: Function definitions are not permitted in this context.'

Could you please advise?

Thanks in advance!

raj k

it is showing Error using adaptcluster_kmeans (line 16)
Not enough input arguments.
what to do plz help

k amin

Dear Author, did you publish this method, if yes, can you provide me with the paper title. regards

Edgar Corzo

Thank you

ankit dixit

@ Edgar, yes you can change it like that.

Edgar Corzo

Thank you. Hence, Can I assume that for grayscale images is the same case? Just I have to change INTERCLUSTER (intercluster = (max(gray(:)/10))).

Y Simson

ankit dixit

Hi Edgar, this code can segment a image in variable number of clusters, it all depends on how may distinct colors are presents in your image. you can control number of clusters by varying difference between clusters, this can be done by changing variable INTERCLUSTER(default is 25). try to change it and see the results.

Edgar Corzo

Is there any form to change the code in order to obtain more than 3 clusters? Or any code with the same process that can obtain n-cluster?

ankit dixit

Hi Kai, Thanks for your appreciation, This code is based on hierarchical clustering algorithm, basically its a binary clustering algorithm.


Does gray scale picture always return K=3?


fantastic implementation!

I want to know the magic behind the code...

How did the code decide the number K.

Do you have any reference I can check?


ankit dixit

@Arjun you can see output clustered image with cluster value:


for any specific cluster, you can write:

for example to see pixels related to cluster 1, you can write:



thanks for quick response ankit..but how to show the segmented output images??
thanks in advance

ankit dixit

Hi arjun you have to just give any rgb image value range between 0 to 255 or you can give a gray image in the same range in input. output will be a clustered image and cluster centers, just write

[clusterimage, clustercenter] = adaptcluster_kmeans(inputimage);

hope you will like it. thank u


please give an example code to use this code..


please give an example code to use this code..


I'm new to Image segmentation and your implementation works perfectly. Thanks :)

Please give me some more info about your algorithm details via online links or email.
Quick response will be much appreciated.

ankit dixit

Hi raneen can you tell me which type of help you needed ??

Raneen Ranoosh

I need Help


Ankit the line and column number are mentioned in error message itself. Can you answer my question regarding version in which you developed it? Also do you assume the two images to have same number of pixels/image size or not?

ankit dixit

Thank you Ramya for your appreciation, Please tell more about your problem, what is your requirement about manual kmeans.

ankit dixit

Hey Vandita, I have check the code. please tell me on which statement you are getting error. Thank you


I am using Matlab 7.8. Will your code work or I have to recode somethings?
I get an error when I run it on a gray image:
??? Error: File: adaptcluster_kmeans.m Line:
72 Column: 3
Expression or statement is
incorrect--possibly unbalanced (, {, or [.

Please suggest modifications.


It was good, I need to know about the manual coding for k - means clustering algorithm in matlab

Apeksha Jain

MATLAB Release Compatibility
Created with R2012b
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

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

Start Hunting!