Image processing performance

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

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 consoleimage=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;endt2=toc()disp(t2)//Rotuine B was saved in a separate filet3=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    endendt4=toc();disp(t4)`

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