File Exchange

image thumbnail


version (19.6 KB) by Micael Couceiro
Multiple Image Segmentation using PSO, DPSO, FO-DPSO and exhaustive methods.


Updated 14 Dec 2012

View Version History

View License

MatLab function for Multiple Image Segmentation using PSO (Particle Swarm Optimization), DPSO (Darwinian PSO), FO-DPSO (Fractional-Order DPSO) and exhaustive methods based on the image histogram shape. The exhaustive method is still in development. The exhaustive method is still in development.

Iout = segmentation(I)
Iout - segmented image.
I - any type of image with multiple intensity levels(e.g., grayscale, color).

[Iout,intensity] = segmentation(I)
intensity - returns the intensity that maximizes the between-class variance. size(intensity)=[size(I,3) level].

[Iout,intensity,fitness] = segmentation(I)
fitness - returns the fitness of the between-class variance. size(fitness)=[size(I,3) 1]

[Iout,intensity,fitness,time] = segmentation(I)
time - returns the CPU computation time
size(time)=[1 1]

[Iout,intensity] = segmentation(I,level)
level - segmentation level. Must be integer ... (Default 2). If level>2
then the segmented image Iout will be an RGB image.

[Iout,intensity] = segmentation(I,level,method)
method - choose the method to perform the multi-segmentation of the image. The pso, dpso, fodpso and exhaustive are the only ones implemented yet. Default pso).

Example: Iout = segmentation(I,4,'pso')

For a detailed description on multiple image segmentation using PSO algorithms please refer to:

Pedram Ghamisi, Micael S. Couceiro, Jón Atli Benediktsson & Nuno M.F. Ferreira. “An Efficient Method for Segmentation of Images Based on Fractional Calculus and Natural Selection”, Expert Systems with Applications, Elsevier, 2012.

Micael S. Couceiro & J. Miguel A. Luz
Created 15/11/2010
Last Update 16/01/2012

Cite As

Micael Couceiro (2020). Segmentation (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (61)

mohamed ahmed

Peace be upon you, please explain this part to me and the program will give me a mistake in it. What should I do?
if size(I,3)==1 %grayscale image
[n_countR,x_valueR] = imhist(I(:,:,1));
elseif size(I,3)==3 %RGB image
[n_countR,x_valueR] = imhist(I(:,:,1));
[n_countG,x_valueG] = imhist(I(:,:,2));
[n_countB,x_valueB] = imhist(I(:,:,3));

Lmax=256; %256 different maximum levels are considered in an image (i.e., 0 to 255)

for i=1:Lmax
if size(I,3)==1 %grayscale image
elseif size(I,3)==3 %RGB image

moom h

Iout = segmentation(I,4,'pso')
%Iout = segmentation(I,4,'dpso')
%Iout = segmentation(I,4,'fodpso')
%Iout = segmentation(I,4,'exhaustive')% in line 3243


Thankyou very much

farrah aslam

Dee T

Can someone explain this part:
vR = ( (vR <= vmin).*vmin ) + ( (vR > vmin).*vR );
vR = ( (vR >= vmax).*vmax ) + ( (vR < vmax).*vR );
xR = ( (xR <= X_MINR(1)).*X_MINR(1) ) + ( (xR > X_MINR(1)).*xR );
xR = ( (xR >= X_MAXR(1)).*X_MAXR(1) ) + ( (xR < X_MAXR(1)).*xR );

Muhammad Ali

great work.

Haram Kim

For users, I noticed that image range maybe 0~255. If you gave it noramlized image, result showes 0s.

Fahad Mahdi

Can you share the test image with me? please email me in

Fahad Mahdi

kirti kaushal

i need a documentary that explains the code. actually i am beginner for matlab

wissal guedri

wissal guedri

Can someone give me a documantary or a description that explains the code please?

Micael Couceiro

The colours of the output image are not relevant - it is a segmentation procedure, so what matters are the different classes of colours. In my case, I decided to choose the colours representing the larger between-class variance. Nevertheless, you can replace the colours for whatever you want, as long as you keep the same different classes.


@Micael Couceiro.. Sir, the image got from this code is different from segmentation done from FCM, Kmeans...In this segmentation, the grayscale image is divided in 3 color..light gray,dark gray and black...why there is no white color comes when I put grayscale image as input?? Plz solve my problem..Plz..if u want i can share my output image too..plz reply..


Can anybody help me to see results of that code?? I want to see the segmented image using PSO,DPSO, FODPSO and exhaustive method in subplot so that i can compare all the can i modify this code and and see all results in one plot? Plz help me..m new to matlab...


@Micael Couceiro..thanks for the reply.. I sent u an email with my image..kindly see that mail..and then see..whether it is segmented or not..I am not able to understand where i can use imshow function to show my results. Kindly give me ur current email id so that i can again send u the email with my gray image. waiting for ur quick reply. :)

Micael Couceiro

begginer01: You need to provide me more details so I can understand what the problem might be. Be sure that you are opening your image as a gray image and not RGB image to start with or, alternatively, after you open your gray image simply use the first depth element of the M x N x D image, i.e., I = I(:,:,1), and then use this new image in the segmentation function.


this is awesome..but i cann't able to see my segmented image results on my gray image.I sent u an email,could you plz check that reply me...thanks a lot..

Jorge Hernandez tapia

Helo, how can I extract every class present in the algorithm output, by the way awesome work

Franck n'guyen

wonderful !
but have you a 3D version applied for :
load mri

Iout=segmentation(D); ?????

thank you again

rahul verma

It worked after a restart ;-)

rahul verma

I tried these,

1) Didn't work
>> I=imread('C:\mtlb\1.jpg');
>> Iout = segmentation(I,4,'pso')

2) >> Iout = segmentation(1,4,'pso')
Undefined function or variable 'segmentation'.

Please help me how to run this code
thanks in advanced

email :

Tirupal Talari

Respected Sir,
im a Research Scholar solving a paper in image fusion using PSO and I need to divide the image (size 256x256) into 3x3, 5x5, 7x7 blocks automatically using PSO please help me. my mail id

shivali k

can u please mail me code to calculate threshold of an image using pso only. I have understood the algo of pso but i am not able to write its code in matlab. Will be very thankful to you if u help me.

Andrew Diamond

Gave it a color image, returned a segmentation image of 0s.

Vasumathi Ganesh

Hello sir,

I tried to run your segmentation.m file, But it shows following error.

Error using segmentation (line 50)
Not enough input arguments.

How to clear this?

Joy Goswami

Ahmad Taher

ABIN joy

Respected Sir,
I already try your coding and it give me a good result. I need your help,how to choose the level for the PSO as 2.
so can u please help me. Thank you


Respected Sir,
i'm doing my ME project in brain tumor image segmentation using PSO i dont know how to calculate the fitness function and how to divide 256x256 image into 3x3,4x4 labels please help mail id


respected sir,
iam not able to get your code. sir please can you mail me the matlab code for image thresholding using pso only. i'll be very thankful to you.

Akshay Gore

Micael Couceiro

Hello Marikhs,

Please, note that deleting the DPSO and FODPSO is irrelevant. As long as you choose 'pso' as method it won't influence at all.

The example given in the header should work on any image:
Iout = segmentation(I,4,'pso')

If you're having a problem working with a specific image just send it to me to and I'll try to check what's going on.


Marikhs Roses

Dear Sir,
I already try your coding and it give me a good result for the first try but after that it cannot give a result. I need your help. Can you please give me the coding for image segmentation using PSO only. the one that u have uploaded having some problem when i try to delete the DPSO and FODPSO. Please email me the code and may God bless you for helping other people.

Micael Couceiro


One of the references is cited on the description of the matlab file:

Pedram Ghamisi, Micael S. Couceiro, Jón Atli Benediktsson & Nuno M.F. Ferreira. “An Efficient Method for Segmentation of Images Based on Fractional Calculus and Natural Selection”, Expert Systems with Applications, Elsevier, 2012.

An alternative would be:

Pedram Ghamisi, Micael S. Couceiro, Fernando M. L. Martins and Jón Atli Benediktsson. “Multilevel Image Segmentation Based on Fractional-Order Darwinian Particle Swarm Optimization”, IEEE Transactions on Geoscience and Remote Sensing, 99, pp. 1-13, 2013.

If you have any problem accessing those e-mail me to and I'll send you my personal copy.



Dear Micael Couceiro,
The functions looks wonderful,but can your give me some reference about this algorithm, if the principle will be presented ,I would be appreciated.Thanks.
My E_mail address

Micael Couceiro

Dear Marikhs Roses,
Can you please tell me more details about what you may need? Did you tried to use this function on your case study first?

Marikhs Roses

i have final year project title 'PSO-based approach in image segmenttation.' I dont really know about my own project because we will learn image processing in another months. so can u please help me. Thank you :)

amal hamed


Could you please suggest a code for color image segmentation using PSO for matlab beginners like me. I am unable to follow the code particularly the fitness function. Could you please suggest a simple code or a fitness function that i could modify to get the color image segmented output.


Micael Couceiro

Dear Gousal,

The help (header of the script) is pretty much straightforward. But, basically, you simply have to open an image using MatLab as, for instance:


Then call the segmentation function as, for instance:

Iout = segmentation(I,4,'pso')

This will result in a image Iout with the same dimensions than I but with only 4 different levels.

Kind regards

shaik gousal

Tell me the execution process of this code .please,,,,

Micael Couceiro

Dear Chen,

You may use nanmax(fitR) instead. This gnores the NaN's and return the maximum value excluding NaN's. That's what I did in the code and thought it was fixed everywhere but seems not.


Dear Micael,
I use this algorithm to catch on to PSO algorithm, and improve the algorithm by doing some experiments. My experiment just use the PSO. I have understood the reason how the NAN happened. But now another question is how to find max(fitR) because the fitR is NAN. Does the procedure stop when it has find max(fitR) is NAN or how to compare NAN?

Micael Couceiro

Dear Chen,

This is a really boring error that bothers me sometimes. By the way, does that happen for the PSO, DPSO and FODPSO or only one of those? I'm asking that cause I remember to implement a way to avoid outputing a fitness function of NaN if that ever occurs but seems that it's not totally fixed...

Now I'll tell you why it happens. As you may know, the algorithms perform the image segmentation maximizing the between-class variance. On the other hand, the computation of the between-class variance depends on the inverse (as denominator) of the probability of occuring a specific level on that image. So, let us suppose that you have a grayscale 8-bit image with all the components except the intensity level 100. This will mean that the probability of occuring 100 will be zero. Hence, if a particle traveling on the search space decides to compute the between-class variance based on the 100 level, its fitness will return NaN since the probability of 100 is zero.

As I didn't implemented a system to avoid non-existant colors, I implemented a way to ignore NaN values and saw it working...and that's why I need to know in which occasions does that happen.


Dear Sir,
Thank you for supplying this code. While the algorithm run, the result of the fitness sometimes is NAN. So I wanna know the reason. Hope for your reply.

Micael Couceiro

Dear Manini,

The code you're presenting is exactly the fitness function, i.e., the between-class variance.

N is the number of particles and level the number of levels within each component (256 for 8-bit images).

You should read my paper
for more details about the fitness function.

In some few words, to compute the between-class variance, and since the number of levels may be different (it depends on the image you're using) a for loop is used. Therefore, the probability distribution and some other relevant parameters are then calculated at each iteration for each colour component and for each particle. In sum, the fitR(j) will represent the fitness function of the red colour component for robot j.

Hope that helps!


Sir, I am using your code for RGB multiobject image. Sir i want to know which is the fitness function here. and
for j=1:N
if size(I,3)==1 %grayscale image
fitR(j)=sum(probR(1:xR(j,1)))*(sum((1:xR(j,1)).*probR(1:xR(j,1))/sum(probR(1:xR(j,1)))) - sum((1:Lmax).*probR(1:Lmax)) )^2;
for jlevel=2:level-1
fitR(j)=fitR(j)+sum(probR(xR(j,jlevel-1)+1:xR(j,jlevel)))*(sum((xR(j,jlevel-1)+1:xR(j,jlevel)).*probR(xR(j,jlevel-1)+1:xR(j,jlevel))/sum(probR(xR(j,jlevel-1)+1:xR(j,jlevel))))- sum((1:Lmax).*probR(1:Lmax)))^2;
fitR(j)=fitR(j)+sum(probR(xR(j,level-1)+1:Lmax))*(sum((xR(j,level-1)+1:Lmax).*probR(xR(j,level-1)+1:Lmax)/sum(probR(xR(j,level-1)+1:Lmax)))- sum((1:Lmax).*probR(1:Lmax)))^2;

sir this is one of the the for loop from your code. can you please explain this for loop. I will be thankful.

Micael Couceiro

Either you read the article recently publised on:

Or you simply compare the fitness value (one of the outputs of the function).

Don't forget that all those algorithm are stochastic and for a correct evaluation you should perform multiple trials.

Mohsen Davarynejad

How to do evaluate the performance of each algorithm? So my question is that how should I believe that for instance the dpso outperforms the pso?


Dear sir,
Thank you very much for providing the code.
Please provide me mathematical description of the fitness function and if u have any published paper on it then a copy of that.

Micael Couceiro

1º open an image in MatLab
I = imread('pic.jpg');

2º Follow instructions in the beginning of the code
Iout = segmentation(I);

3º See the result


how to run it sir


Micael Couceiro

You're welcome

Majid Al-Sirafi

wonderful program,thank you dear

Micael Couceiro

Kyle, I just uploaded a new version with a new segmentation method btw (FO-DPSO).

The segmentation methods are based on the traditional PSO presented by Kennedy and Eberhart in 1995, the Darwinian PSO presented by Tillett et al in 2005 (see more about it in and the Darwinian PSO extension using fractional calculus presented by me and other authors in the Fractional Signals and Systems Symposium in 2011. This last paper will be soon available.

Anyway, this script basically uses such optimization methods to find the maximum between-classes variances. Another more detailed paper describing this script will soon be published.

Kyle Wang

Could you indicate the paper that the code is implemented based on?

Micael Couceiro

The intensity will have the same value than the intensity level that presents the higher between-class variance.
In other words, if it is presenting a level of 50 it means that this is the optimal level.

Anyway, you can easily change this with the matlab find function as:
eg: [a,b]=find(IMAGE==50);


Hello Micael,
I'm using your function to segment my grayscale images. However the max intensity of the output image is only 50. How do you set it to be 255? Thanks!

Muhammad Nawaz

Strongly recommended for multicolour and multi objects images.

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

Inspired: TRIM: Triangulating Image

Community Treasure Hunt

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

Start Hunting!