I have the following code snippet in matlab with two 'for' loops: 'I' is a binary image that has been preallocated.
...
[x,y] = find(bwmorph(I,'endpoints'));
n=numel(x);
m=numel(x)-1;
n=m+1;
r=i+1;
for i= 1:m
for j = r:n
I=linept(I, x(i), y(i), x(j), y(j));
end;
end;
...
The linept function is given below.Its from the Matlab File Exchange:
function result=linept(matrix, X1, Y1, X2, Y2)
result = matrix;
a=max(1, X1);b=sign(X2 - X1);c=max(1, X2);
for x=a:b:c
y = round(f(x, X1, Y1, X2, Y2));
if y > 0
result(x, y) = 1;
end
end
d=max(1, Y1);e=sign(Y2 - Y1);g=max(1, Y2);
for y=d:e:g
x = round(f2(y, X1, Y1, X2, Y2));
if x > 0
result(x, y) = 1;
end
end
function y=f(x, X1, Y1, X2, Y2)
a = (Y2 - Y1)/(X2 - X1);
b = Y1 - X1 * a;
y = a * x + b;
function x=f2(y, X1, Y1, X2, Y2)
if X1==X2
x = X1;
else
a = (Y2 - Y1)/(X2 - X1);
b = Y1 - X1 * a;
x = (y - b)/a;
end
Due to the many 'for' loops and function calls, this code is running very slowly.It runs fast for a simple image with few end points, but it takes a lot of time when the number of edges is more.It is slightly faster if the size of the image is reduced.I tried to vectorise it and have preallocated some variables, but there isn't much improvement.Can anyone help me regarding how to vectorise codes that call functions in loops.Thank you