function outROI = PS_roiEnhance_threshold(tempCrop,S,M,B)
%1. This function removes background noise for the cropped ROI.
%2. This function also identifies the dominant object within the cropped
%   and remove other smaller objects.
%3. Input variable is the cropped ROI and output variable is the cleaned up
%   ROI.
%
% Created By: Kaichang CHENG, Jul 10,2019
%**************************************************************************
[m,n]=size(tempCrop);
%h = fspecial('gaussian',3,0.5);%创建一个滤波器
%tempCrop=imfilter(tempCrop,h,'symmetric');
%
% tempCrop0 = padarray(tempCrop, [1, 1], 'symmetric', 'both'); %以最大值扩充1圈
% tempCrop1=medfilt2(tempCrop0,[3,3]);
% tempCrop=tempCrop1(2:(m+1),2:(n+1));
%
% if m*n>2000
%     BW1a= ~FengBW(tempCrop,[7,7],3, 0.155, 0.355, 0.025, 2);
% else
%     BW1a=~imbinarize(tempCrop);
    
        BW10 = thresholdLocally(tempCrop, [S, S]);      %在局部窗口内使用Otsu进行分割
         %BW10 = sauvola(tempCrop, [3, 3],0.34,'replicate');
         %BW10 = sauvola_plankton(tempCrop, [S, S],0.34,'replicate');
        tempCrop1a = imresize(tempCrop, size(BW10) + 2);%保证下一步的处理结果的尺寸为原图尺寸
    
        % BW1a = imbinarize(tempCrop);      %使用Otsu进行分割
        % tempCrop1a = imresize(tempCrop, size(BW1a)+2);%保证下一步的处理结果的尺寸为原图尺寸
        BW100 = gradient_edge_V2(tempCrop1a);
        %BW1a = (imcomplement(BW10)) | BW100;
        BW1a = ~BW10 | BW100;

%end
if any(BW1a(:))
    
    BW1=BW1a;
    %Remove smaller ROIs
    se = strel('disk',M);
    closeBW = imclose(BW1,se);
    BW2 = imfill(closeBW, 'holes');
    %BW3 = bwmorph(BW2, 'clean');%去除图像中孤立的亮点，比如， 一个像素点， 像素值为1， 其周围像素的像素值全为0， 则这个孤立的亮点将被去除；
    BW3 = bwareafilt(BW2, 3);   % 取面积最大的前3个连通域
    props = regionprops(BW3, 'boundingbox','centroid','FilledImage');
    props_cell=struct2cell(props);
    if size(props_cell,2)==3
        one=norm(props(1).Centroid-[n/2,m/2]);
        two=norm(props(2).Centroid-[n/2,m/2]);
        three=norm(props(3).Centroid-[n/2,m/2]);
        [~,in]=min([one,two,three]);
    elseif size(props_cell,2)==2
        one=norm(props(1).Centroid-[n/2,m/2]);
        two=norm(props(2).Centroid-[n/2,m/2]);
        [~,in]=min([one,two]);
    else
        in=1;
    end
    BW4=props(in).FilledImage;
    %subplot(132),imshow(BW4);title('二值化效果')
    
    %tempCrop = imresize(tempCrop, size(BW4));
    % props = regionprops(BW4, 'boundingbox');
    tempBox1a = props(in).BoundingBox;
    outROI = imcrop(tempCrop, tempBox1a);
    if isempty(outROI) == 0 || isempty(BW4) ==0
        outROI = tempCrop;
    else
        BW5 = imresize(BW4, size(outROI));
        if B==0
            back=mean(tempCrop(:));
        else
            back=255;
        end
        outROI(~BW5) = back;                            %以原始ROI的最大值填充背景
        outROI = padarray(outROI, [1 1], back, 'both'); %以最大值扩充1圈
    end
else
    outROI = tempCrop;
end
end