clear ag;
clear ag2;
%ag=aga; %old movie
ag=agb; %new movie

mask=[0 -1 0;-1 5 -1; 0 -1 0];  

for i=1:size(ag,3)
image=ag(1:240,1:320,i);
image=medfilt2(image,[4 4]);  %median filter
ag2(1:240,1:320,i)=imfilter(image, mask);   %sharpen the frames
end;

ag=ag2;

%Compute the background image BG1 from the fames as the mean of all frames. 
BG1=mean(ag,3);  

%Compute the pixelwise standard deviation in each pixel 
BGstd=std(ag,0,3); 

%For all frames, show all the difference images, thresholded by 2 standard deviations.
for i=1:size(ag,3)
image=ag(1:240,1:320,i);
cc=abs(image-BG1)>(2.2*BGstd);
imshow(cc);
pause(0.01);
end;