saving . . . saved
0
Image processing performance
Title
Question

Hey guys,

I have a short question: I want to convert a grayscale-image (matrix of floats from 0 to 1) into a binary image having only 0 and 1, depending on a set threshold.
Therefore I wrote this two alternative routines:
Routine A
for i=1:length(image)
        if image(i) < threshold then
            image(i) = 0;
        else
            image(i) = 1;
        end
        blackwhite = image;
    end
Routine B
for y=1:length(image(:, 1)) 
    for x=1:length(image(1, :))
        if image(y, x) < threshold then
            blackwhite(y, x) = 0;
        else
            blackwhite(y, x) = 1;
        end
    end
end
I expected that Routine A should be quicker, as all the operations are done within the "image"-matrix and only at the end all values are copied to the new variable. Furthermore it uses only one for-loop instead of two.
However, using the tic() toc() commands I see that Routine B is about three times faster than Routine A... Can someone explain me why? Iam still new to this topic and try to get to know how to make such analyses as fast as possible..
Thanks, Hackmet


Scilab 31-05-17, 5:19 p.m. Hackmet

Answers:

0

In Routine A, if you comment the line- blackwhite=image;, you'll get comparable results. When I ran the code after commenting the line, I got the run time to be either equal or routine B run time was higher than routine A.

The code I've used is given below

//This was declared on the console

image=rand(5,1000);
image1=image;
threshold=
0.4;

//Routine A was saved in a separate file
t1=tic()
for i=1:length(image)
if image(i) < threshold then
image(i) = 0;
else
image(i) = 1;
end
//blackwhite = image;
end
t2=toc()
disp(t2)

//Rotuine B was saved in a separate file
t3=tic()
for y=1:length(image1(:, 1))
for x=1:length(image1(1, :))
if image1(y, x) < threshold then
blackwhite(y, x) = 0;
else
blackwhite(y, x) = 1;

end
end
end
t4=toc();
disp(t4)


06-06-17, 12:34 p.m. shamika


0

Thanks for your answer! And yes, Iam dumb :D :D

The problem is, that I accidentally have put the "blackwhite = image" command within the for-loop, so the script had to define the variable thousands of times...
If I put it outside the for-loop, routine A takes 0.08 s, compared to the o.25 s for routine B.

06-06-17, 1:41 p.m. Hackmet


Log-in to answer to this question.