% This fnction is used to get a background image. Sine we aim to locate the motion within a static
% backgroud, we suppose that moving objects stay at a position in background very shortly then move to 
% other positions. Then the background pixel positions which was covered by moving objects is now disclosed.
% Because any background pixels will be disclosed after moving objects leave that position,we can get every
% backgroud pixel's value. The following is the steps:
% first, we had computed adjacent video frame difference,and we got a frame difference sequence PDIFF(x,y,:,k),
% which k is the frame number. here PDIFF records every pixel's variation curve along time axis at coordinat
% (x,y). then at this function we compute the largest continuous segment length, in this segment PDIFF(x,y,:,:) 
% is 0, which  reflects the Background pixel at (x,y) is not covered by moving objects in a longest time.
% finaly, we select the middle frame number,supposed framenum, according this largest continuous segment length 
% PDIFF(x,y,:,:), and select the original pixel value I(x,y,:,framenum) as the corresonding background pixel 
% value.

function backGround = getbackground()
load result

% Compute every pixel's value in background image
for x=1:numrow
    for y=1:numcol
        seg_len=0;large_len= 0;
        seg_start=1;seg_end=1; 
        framenum=1;
        
        % for k = 1:noOfFrameImages-1
        j = 1; k=1;
        while  j<noOfFrameImages-1               
           while PDIFF(x,y,1,k) ~= 0 & k< noOfFrameImages-1
               k=k+1;
               if k>noOfFrameImages-1
                   break;
               end
           end
           seg_start = k;% here we found the pixel difference value = 0;
           
           while PDIFF(x,y,1,k) == 0 & k<noOfFrameImages-1
               k = k+1;
               if k>noOfFrameImages-1
                   break;
               end
           end
           seg_end = k-1;
           seg_len=seg_end+1-seg_start;
           if(seg_len >large_len)
               large_len = seg_len; %the largest length of the segment which corresponing pixel value difference is 0;
               framenum = int8((seg_end + seg_start)/2); % we select the middle frame among the segment;
           end
           j=k;
       end
       pixelvalue = I(x,y,:,framenum);
%      select the corresponding pixel in framenum frame as the background pixel value;
%      backGround is the static background image in a video sequence with
%      moving object;
%      here we get and assign every pixel value for bacaground image;
       backGround(x,y,:) = pixelvalue;

       
       
       
   end
end
figure;
imshow(backGround);

save backgroundimage backGround;

return;

