%% lab 10: Batch Processing - Wednesday, 2016-04-20
% In this lab, you will tie together the components from Lecture 11 to
% develope a MATLAB motion tracking program.

%% Get File List

rootdir = 'set1/';
ext = '.jpg';

files = dir(fullfile(rootdir, ['*' ext]));
dirIdx = [files.isdir];
files = {files(~dirIdx).name}';
numFiles = length(files);

%build full file path
for i = 1:numFiles
    files{i} = fullfile(rootdir,files{i});
end

%% Compute Background Image

bg = double(imread(files{1}));
for i = 2:numFiles
    tmp = double(imread(files{i}));
    bg = bg + tmp;
end
bg = uint8(bg/numFiles);
bg = mtpreproc(bg);

%% Batch Process

for i = 1:numFiles
    img = imread(files{i});
    img = mtpreproc(img);
    
    diffimg = img-bg;
    diffimg = medfilt2(diffimg, [5 5]);
    mask = diffimg > 25;


    maskx = any(mask, 1);
    masky = any(mask, 2);

    minmax = @(x) [min(x), max(x)];
    x = minmax(find(maskx));
    y = minmax(find(masky));

    imshow(img);
    if ~isempty(x)
        hold on
        rectangle('Position', [x(1) y(1) x(2)-x(1) y(2)-y(1)], ...
            'EdgeColor', 'green')
        hold off
    end
    pause(0.1)
end
    


