Segmenting brain images (Dicom format) using region-growing algorithm I have a list of images in a folder where num denotes the index of image and I used num to run the iterations in a "for loop". The code is supposed to segment brain part from the brain CT images. Here is the link for region growing algorithm.

How do I increase the performance of my region-growing algorithm?

% CORD_XY(1),CORD_XY(2) is the seed point
% LEN Denotes the number of images in a folder    
% num is used to iterate in "for loop"
% "img" here is single image from the folder in DICOM format

for num= 1:LEN 
    img = dicomread(files(num,1).name);
    [row, col] = size(img);
    th = 20;
    diff = 10;

    J = regiongrowing(img, CORD_XY(1), CORD_XY(2), th);
    value1 = sum(sum(J &gt; 0));

    if num &gt; 10)
        th = 55;
    elseif num &lt;= 10
        while diff &lt; 0.2 * value1 &amp;&amp; diff ~= 0 &amp;&amp; th &lt; 60
            value1 = sum(sum(J &gt; 0));
            th = th + 10;
            J = regiongrowing(double(img), CORD_XY(1), CORD_XY(2), th);
            value2 = sum(sum(J &gt; 0));
            diff = value2 - value1; 
        end
    end
end  

J = regiongrowing(img, CORD_XY(1), CORD_XY(2), th-10);
I don't have the Image Processing Toolbox, so I can't test your code, but I'll go through what I can.

Never do diff = 10; diff is a useful builtin function in Matlab, so using it as a variable name will cause the function to be useless. The same goes with max, sum, size and so on.

value1 = sum(sum(J &gt; 0)); is a bit faster than value1 = sum(J(:)&gt;0);, so with regards to performance you did the right thing. In my opinion however, sum(J(:)&gt;0) is a bit cleaner, and it can also be scaled to more dimensions.

Instead of elseif N &lt;= 10 you can simply do else, as they mean the same thing in this context.

If it takes 4-5 iterations pretty consistently, then maybe you can increase the initial value of th to e.g. th = 40. It will result in fewer iterations for most images, so a faster algorithm. You might benefit from guessing a good value, run the algorithm, if you don't hit convergence, jump to a lower value. This will perform better for most of the images, but will be slower for some. In total, it's likely faster.