From: remey22 on
Hi, i am looking for help to optimize the for loop in MATLAB code;i am working with video file, and try to extracted the image diffrence in each consecutive frames
>
> my code is as below ;
> %==========================================================
> mov=aviread('test_41.avi'); read the avifile
>
> for n = 1:length(mov-1);
>
> a1 = frame2im(mov(n));
> b1 = frame2im(mov(n+1));
> Fdif = imabsdiff(b1,a1); % substract frame
> Fdif = rgb2gray(Fdif); % convert to grey
> imshow(Fdif);
> hold on;
> drawnow;
> hold off;
> end
>
> %============================================================
>
> could anyone suggest how to optimize the for loop, so that it can increase the execution speed.
>
> thanks..
From: ImageAnalyst on
You could try converting to gray before subtracting. Use tic and toc
to see if that makes it faster - it may or may not. You could also
get rid of the hold on/off - I'm not sure what those are supposed to
do. Why do you want to put hold on?

If you don't need to display, you could get rid of the imshow(), but I
think you do want to display because there's nothing else that your
script does after the subtraction so I guess it's purely for viewing.
From: Jan Simon on
Dear remey!

> mov=aviread('test_41.avi'); read the avifile
> for n = 1:length(mov-1);
> a1 = frame2im(mov(n));
> b1 = frame2im(mov(n+1));
> Fdif = imabsdiff(b1,a1); % substract frame
> Fdif = rgb2gray(Fdif); % convert to grey
> imshow(Fdif);
> hold on;
> drawnow;
> hold off;
> end

You apply FRAME2IM twice for each frame. Avoid this e.g. like this way:

mov=aviread('test_41.avi'); read the avifile
a1 = frame2im(mov(1));
for n = 2:length(mov) % TYPO in the original post?! "length(mov-1)"
b1 = frame2im(mov(n));
Fdif = rgb2gray(imabsdiff(b1, a1)); % convert difference to grey
a1 = b1;
imshow(Fdif);
drawnow;
end

I do not have the image toolbox. You could try if IMABSDIFF if faster, when it is inlined:
Fdif = abs(b1 - a1);
Does IMSHOW delete already displayed images? If not, use IMAGE for displaying, remember the handle and replace just the CDATA property in every loop.

mov=aviread('test_41.avi'); read the avifile
a1 = frame2im(mov(1));
ImageH = [];
for n = 2:length(mov) % TYPO in the original post?! "length(mov-1)"
b1 = frame2im(mov(n));
Fdif = rgb2gray(imabsdiff(b1, a1)); % convert difference to grey
a1 = b1;
if isempty(ImageH)
ImageH = image(FDif);
axis('Image');
else
set(ImageH, 'CData', Fdif);
end
drawnow;
end

But this might be slower - I do not have IMSHOW for testing.

Good luck, Jan
From: remey22 on
thanks Jan for your advice,
i have executed using your code and there is an increase in execution time especially when imshow(Fdif) command being replaced by command image(Fdif).

thanks a lot..
remey
From: remey22 on
ops.. sorry, the execution time not increased, but decreased :)