function SBM_processing_pipeline(dataset_path, result_path)
% The pipeline for processing the SBMnet dataset. This pipeline will
% generate a 'results' folder in the 'result_path' to save one estimated
% background image for each video generated by a background modeling
% method.
%
% Modify the line 28 to call you method, in the form of:
%       BG_result = YOUR_METHOD(video_path);
% where 'video_path' is the input path of a video;
%       'BG_result' is the estimated background image.
%
% input:
%   dataset_path: path of the SBMnet dataset folder;
%   result_path: path of the results folder.

category_list = {'backgroundMotion', 'basic', 'clutter', 'illuminationChanges', 'intermittentMotion', 'jitter', 'veryLong', 'veryShort'};

for category_id = 1 : length(category_list)
    category = category_list{category_id};
    category_path = fullfile(dataset_path, category);
    videos = dir(category_path); videos = videos(3 : end);  %remove the '.' and '..' folder
    for video_id = 1 : length(videos)
        video = videos(video_id).name;
        display(['Now processing: "' category, ' / ', video, '" video']);
        video_path = fullfile(category_path, video, 'input');
        
        %%%%%%%%%%%%%%%%%%%%call your method%%%%%%%%%%%%%%%%%%%%%%
        BG_result = BG_median(video_path);
        
        %save the image
        result_video_path = fullfile(result_path, 'results', category, video);
        if ~exist(result_video_path, 'dir'), mkdir(result_video_path); end
        imwrite(BG_result, fullfile(result_video_path, 'RESULT_background.jpg'));
    end
end

end

function BG_result=BG_median(video_path)
%
% Basic temporal median filter function which loads every file in the
% video_path and compute a temporal median filter on it.
%
    fileList = dir(video_path);
    currentImage = imread(fullfile(video_path,fileList(3).name), 'jpg');
    [height width nbChan] = size(currentImage);

    videoFrames = zeros(height,width,nbChan,size(fileList,1)-2,'uint8');
    j=1;
    for i = 3:size(fileList,1)
        videoFrames(:,:,:,j) = imread(fullfile(video_path,fileList(i).name), 'jpg');
        j=j+1;
        if mod(j,100)==0
            fprintf('%d / %d\n',j,size(fileList,1));
        end
    end
    BG_result = median(videoFrames, 4);
    
end

        
        