MATLAB: Please suggest some solution to this code if any mistakes

image segmentationMATLAB

function region=eregiongrowing(f)
region=cell(size(f)); %Region matrix with same size of image,storing the labels of grown region
[m,n]=size(f);
seed=[m/2,n/2];%position of seed(x,y)
rcount=1;%counter to keep track of current region being grown
i=1;
j=1;
pg=seed;%pg is stack to sore pixels to grow
x1=im2single(f);
%Adaptive Threshold code start;
Err = 1;
T0=(max(max(x1))+min(min(x1)))/2;
while Err > 0.0001,
u1=0;
u2=0;
cnt1=0;
cnt2=0;
for i=1:m
for j=1:n
if x1(i,j)<= T0
u1=u1+x1(i,j);
cnt1=cnt1+1;
else
u2=u2+x1(i,j);
cnt2=cnt2+1;
end
end
end
u1=u1/cnt1;
u2=u2/cnt2;
T=(u1+u2)/2;
Err=abs(T-T0);
if Err > 0.0001
T0=T;
end
end
y=im2bw(f,T0);
%threshold end
L=bwlabel(y,8);% labelling of region
h=f(:,:,1);
s=f(:,:,2);
v=f(:,:,3);
while ~isempty(pg)%while pg is not empty
cp=pg;% cp -8 neighbours
double(cp);
i=i-1;
for k=1:8
if region(cp(k))~=L;%if region(cp(k)is not labelled
%code to find similarity using Euclidean distance
for i=1:8
for j=1:8
Dh=(h(x+i,y+j,1)-h(x,y,1)).^2;
Ds=(s(x+i,y+j,2)-s(x,y,2)).^2;
Dv=(v(x+i,y+j,1)-v(x,y,1)).^2;
end
end
d=sqrt(Dh+Ds+Dv);
if(d<T)% threshold value founded in adaptive threshold
region(cp(k))=rcount;
i=i+1;
pg=cp(k);
else
j=j+1;
bp=cp(k);% bp is stack to store boundary pixels of grown region
end
end
end
end
while ~isempty(bp);
j=j-1;
rcount=rcount-1;
i=1;
pg(i)=seed;
end
Getting Following message
??? Subscript indices must either be real positive integers or logicals.
Error in ==> eregiongrowing at 48 if region(cp(k))~=L;%if region(cp(k)is not labelled
Please Check the code and tell
me whether I am doing some mistakes anywhere in the code,if so please suggest
the solution

Best Answer

It is a very general question to ask the forum for searching a mistake anywhere else in the code. Because the code does not contain a suitable number of comments, we cann only guess, what the lines should achieve. And this guessing is based on the code only. So how could we find the difference between what the code does and what you want it to do?!
At first I would mark the code and hit Cmd-I for a clean indentation, before I post it in the forum.
Then note, that the line double(cp); converts the variable cp to a double temporarily, but does not store the result anywhere, such that this is a waste of time. Do you want:
cp = double(cp);
This looks strange:
for i=1:8
for j=1:8
Dh=(h(x+i,y+j,1)-h(x,y,1)).^2;
Ds=(s(x+i,y+j,2)-s(x,y,2)).^2;
Dv=(v(x+i,y+j,1)-v(x,y,1)).^2;
end
end
Here Dh, Ds, Dv are overwritten in each iteration. Then only the value of i=8 and j=8 are stored, so why do you compute the rest?
pg(i)=seed; must fail, when seed is not a scalar.
The actual problem:
seed=[m/2,n/2];
...
pg=seed;
...
cp=pg;
...
if region(cp(k))~=L % ERROR
This must fail, if m or n is odd, because than cp contains non-integer values.
Related Question