% Preprocess ROI containing the hippocampus to simplify the localization.
% The only mandatory parameter is the image (hip_img). You can change
% other parameters like image size (image_side), images average mean and
% standard deviation (um, ustd), minimum area covered by a hippocampus
% (min_area_hippo), minimum number of connected components
% (min_conn_components). It returns the processed b/w image.

function roi_img = preprocess_roi(hip_img, image_side, um, ustd, min_area_hippo, min_conn_components)

    if ~exist('image_side','var')
        image_side = 800;
    end
    if ~exist('um','var')
        um = 209.8621/255.0; %these two values were obtained by the training set
    end
    if ~exist('ustd','var')
        ustd = 26.2777/255.0;
    end
    if ~exist('min_area_hippo','var')
        min_area_hippo = 12.0; %minimum area covered by a hippocampus
    end
    if ~exist('min_conn_components','var')
        min_conn_components = 6;
    end
    m=mean2(hip_img);
    st=std2(hip_img);
    tmp_roi=(double(hip_img)-m)*ustd/st+um;
    tmp_roi = adapthisteq(tmp_roi);
    tmp_roi(hip_img > (225/255.0)) = 1;
    tmp_roi(hip_img < (30/255.0)) = 0;
%     tmp_roi = adapthisteq(tmp_roi);
    th_level = graythresh(tmp_roi);
    tmp_roi = 1-im2bw(tmp_roi,th_level);
    tmp_roi = imerode(tmp_roi, strel('ball',2,0,0));
    roi_img = zeros(size(tmp_roi));
    % tmp_roi = tmp_roi*255;

    if mean2(tmp_roi) < min_area_hippo/255.0
        roi_img = tmp_roi;
    else
        CC = bwconncomp(tmp_roi,8); % A scalar connectivity specifier must be 1, 4, 6, 8, 18, or 26.
        numPixels = cellfun(@numel,CC.PixelIdxList);% number of pixels of each connected component
        [ordered,idx] = sort(numPixels,'descend');
        con_component=min_conn_components; %minimum number of con_components
        for c=1:con_component
            roi_img(CC.PixelIdxList{idx(c)}) = 1;
        end
        while mean2(roi_img) < min_area_hippo/255.0 && con_component < length(numPixels)
            roi_img(CC.PixelIdxList{idx(con_component)}) = 1;
            con_component = con_component + 1;
        end
    end
	clear CC
	clear tmp_roi
    roi_img=imresize(roi_img,[image_side image_side]);
end