function assignment1_601
load ../SurvTestFrames.mat;
BG1=sum(ag,3)/size(ag,3);
BGstd=std(ag,0,3);   
V=zeros(size(ag,1),size(ag,2),size(ag,3));
for k=1:size(ag,3)
    image=ag(:,:,k);
    Object=image;
    Object(abs(image-BG1)>2*BGstd)=1;
    Object(abs(image-BG1)<=2*BGstd)=0;
    V(:,:,k)=Object;
    subplot(1,2,1);
    imshow(Object);
    subplot(1,2,2);
    imshow(image);
   
    pause(0.1);
end
close all;
figure(1);imshow(BG1); % show the first background
pause;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
avg=sum(V(:))/size(V,3);
flag=zeros(1,size(V,3));
for k=1:size(V,3)
    image=V(:,:,k);
    if sum(image(:))>avg % it moves a lot
        flag(k)=1;
    end
end

BG2=sum(ag(:,:,~flag),3)/sum(~flag);
figure(2);imshow(BG2);% show the second background
pause;
figure(3);
V2=zeros(size(ag,1),size(ag,2),size(ag,3));
for k=1:size(ag,3)
    image=ag(:,:,k);
    Object=image;
    Object(abs(image-BG2)>2*BGstd)=1;
    Object(abs(image-BG2)<=2*BGstd)=0;
    V2(:,:,k)=Object;
    subplot(1,2,1);
    imshow(Object);
    subplot(1,2,2);
    imshow(V(:,:,k));
   
    pause(0.1);
end
figure(4);imshow(histeq(abs(BG1-BG2)));% show the difference between two background