
%%%------------------------------------------------------------------------
%%% Image Processing HW1. part 2
%%% Xin Li, Feb 4,2008
%%%------------------------------------------------------------------------

% clear;
% close all;
% clc;
% % DATAPATH = 'C:\Documents and Settings\Administrator\Desktop\08Spring\image_processing\HW1\';
% DATAPATH = '/usr/home/h/133/tua739/image_processing/';
% filename = strcat(DATAPATH,'SurvTestFrames.mat');
% load(filename,'ag');

% filename = strcat(DATAPATH,'v.mat');
% load(filename,'v');

% filename = strcat(DATAPATH,'BG1.mat');
% load(filename,'BG1');

% for i=1:size(ag,3)
%     imshow(ag(:,:,i));
%     title(['Number',num2str(i)]);
%     pause(1);
% end

index = find(v<mean(v))
BG2 = mean(ag(:,:,index),3);
BGstd = std(ag(:,:,index),0,3);
[row, col] = size(ag(:,:,1));
M = [];
for n = 1:size(ag,3)
    foreground = zeros(row,col);
    image = ag(:,:,n);
    foreground(abs(image-BG2)>2*BGstd) = 1;
%     C = xor(foreground,image);
    vv(n) = length(find(foreground == 1));
    imshow(foreground);
    title(['frame',num2str(n)])
%         if n >= 30
% % %             pause
% %             saveas(gcf,['The thirty frame(part2).png']);
%         end
    M=[M getframe()];
end
movie2avi(M,'System2.avi');
colormap gray;
bar(vv);
title('Foreground Pixels(second part)');
saveas(gcf,['second bar.png']);
close;

% %%%-----------------the movie will shown here----------------------------
% for i=1:size(ag,3)
%     %     imagesc(double(ag(:,:,i) - BG2));
%     %     title(['Number',num2str(i)]);
%     imagesc((ag(:,:,i) - BG2));
%     title(['Number',num2str(i)]);
%     pause(0.1);
% end
% 
% figure;
% for i=1:size(ag,3)
%     %     imagesc(double(ag(:,:,i) - BG2));
%     %     title(['Number',num2str(i)]);
%     imagesc(double(ag(:,:,i) - BG2));
%     title(['Number',num2str(i)]);
%     pause(0.1);
% end
% %%%----------------------------------------------------------------------


I = abs(BG2-BG1);
J = histeq(I);
figure;
subplot(2,2,1);
imagesc(I);
title('BG2-BG1');

subplot(2,2,3);
imagesc(BG2);
title('BG2');

subplot(2,2,2);
imhist(I,64);
title('histogram of BG2-BG1 ');

subplot(2,2,4);
imhist(J,64);
title('histeq of BG2-BG1');
saveas(gcf,['BG2-BG1.png']);
close;


