Long Computation Image Processing

2 views (last 30 days)
The script below is taking very long to compute mo1 (a few minutes). When "(1/(D(x+1,y+1)+1))" is removed the computation time goes down a lot (few seconds). Or when if statements are used involving D(x+1,y+1) it is still fast.
A=imread('leaf.jpg');
A = im2bw(A);
[m,n]=size(A);
BW = edge(A);
D = bwdist(BW);
m1o=0;
for x=0:m-1 %Image is 1403X2508
for y=0:n-1
m1o=m1o+(x)*A(x+1,y+1)*(1/(D(x+1,y+1)+1));
end
end
m1o
Why is the time so long and how do I reduce the computation time? The function is calculating mo1 based on the distance the pixel is to the boundary. Is there another way to do this? I have used many if statements to approximate the same thing (and they run fast) but I really need the function.

Accepted Answer

Sean de Wolski
Sean de Wolski on 5 Feb 2014
Your for-loops can be replaced with some array and linear algebra computations. Also, D is returned as a single and you're running into precision errors. I'd recommend casting it to double:
A=imread('cameraman.tif');
A = im2bw(A);
[m,n]=size(A);
BW = edge(A);
D = double(bwdist(BW));
msd = sum((0:m-1)*(A./(D+1)));
  2 Comments
Minhal
Minhal on 5 Feb 2014
Thanks! Yeah the precision errors thing was it. I converted it into double and works like a charm now :D
I don't know how to debug code so I couldn't find it myself.
I'm also calculating other things in the code so I need the for loops but converting D to double has done the trick.
Minhal
Minhal on 5 Feb 2014
Also, thank you for your prompt reply really appreciate it.

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 5 Feb 2014
Out of curiosity, what if you recode as
m1o = m1o + (x)*A(x+1,y+1)/(D(x+1,y+1)+1));
and then why not recode further,
for x = 0 : m-1
mlo = mlo + sum( x .* A(x+1, :) ./ (D(x+1,:)+1);
end
and then, if I have worked things out correctly, collapse it all to
mlo = sum( (0 : m-1) * (A ./ (D+1)) );

Community Treasure Hunt

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

Start Hunting!