%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); 

%Show the difference image of the example image
image=ag(1:240,1:320,29);
cc=abs(image-BG1)  > (2*BGstd);
imshow(cc);       

%For all frames, show all the difference images, thresholded by 2 standard deviations.
for i=1:56
image=ag(1:240,1:320,i);
cc=abs(image-BG1)  > (2*BGstd);
imshow(cc);
pause(0.03);
v(i)=sum(cc(:)); %Create a 1x56 vector 'v', that contains the number of foreground pixels in each frame. 
end;
bar(v); %Plot the vector v 

%Analyse the vector v. Identify all frames with a foreground activity that's less than the mean activity.
ag2=ag(1:240,1:320,find(v<mean(v)));

%Build a second version of the background (BG2) using these frames only
BG2=mean(ag2,3); 

%Create the std using these frames only
BGstd2=std(ag2,0,3);

%Show the difference image of the example image using BG2
image=ag(1:240,1:320,29);
cc=abs(image-BG2)  > (2*BGstd2);
imshow(cc);

%For all frames, show all the difference images, using BG2 and BGstd2
for i=1:56
image=ag(1:240,1:320,i);
cc=abs(image-BG2)  > (2*BGstd2);
imshow(cc);
pause(0.03);
v(i)=sum(cc(:));
end;
bar(v);

%Show the difference between the 2 background images
histeq(abs(BG2-BG1)); 