%%%% Howework 1: Detecting Moving Objects
%%%% Shusha Li, Feb 3rd, 2008
%%%% 'ag' is a 240*320*56 matrix containing 56 grayvalue images taken from
%%%% a movie, which is our data

%clear;
close all;
%load SurvTestFrames
% compute the background image BG1 from the frames as the mean of all
% frames.
BG1=sum(ag,3)/size(ag,3);
imshow(BG1);

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

% for all frames, show the difference-images, thresholded by 2 standard
% deviations
figure;
for fIndex = 1:size(ag,3)
    frame = ag(:,:,fIndex);
    frame(find(abs(frame-BG1)>2*BGstd))=1;
    frame(find(abs(frame-BG1)<=2*BGstd))=0;
    subplot(7,8,fIndex);
    imshow(frame);
    % save the frames after doing threshold to frame1
    frame1(:,:,fIndex)=frame;
    title(sprintf('%d',fIndex));    
end

% create a 1*56 vector 'v' contains the number of foreground pixels in each
% frame. Plot the vector v (e.g. using 'bar(v)') and compare its
% correspondence to the movie frames. 
figure;
v = zeros(1,56);
for fIndex = 1:size(ag,3)
    % figure,imshow(frame1(:,:,fIndex));
    v(1,fIndex)=sum(sum(frame1(:,:,fIndex)==1));
end
bar(v);

% improve the background by filterring frames
w=v; counter=1;
w(find(w<1000))=0;
SIZE=sum(w<1000);%if w>1000, i think that the prof is coming in
BG3=zeros(size(ag,1),size(ag,2),SIZE);
for fIndex = 1:size(ag,3)
    if(w(fIndex)<=0)
        BG2(:,:,counter)=ag(:,:,fIndex);
        counter=counter+1;
    end
end
BG2=sum(BG2,3)/SIZE;
figure,imshow(BG2);

% compute the std again using BG2
BG2std=std(ag,0,3);
figure;
for fIndex = 1:size(ag,3)
    frame = ag(:,:,fIndex);
    frame(find(abs(frame-BG2)>2*BG2std))=1;
    frame(find(abs(frame-BG2)<=2*BG2std))=0;
    subplot(8,8,fIndex);
    imshow(frame);
    frame1(:,:,fIndex)=frame;
    title(sprintf('%d',fIndex));    
end
%show the difference between the 2 background
figure;
diff=histeq(abs(BG2-BG1));
bar(diff);