result1_1=zeros(n_rows,n_cols);
result1_2=zeros(n_rows,n_cols);
result1_3=zeros(n_rows,n_cols);
result1_1(r+1:n_rows-r,r+1:n_cols-r)=(result_1(r+1:n_rows-r,r+1:n_cols-r)<thresh);
result1_2(r+1:n_rows-r,r+1:n_cols-r)=(result_2(r+1:n_rows-r,r+1:n_cols-r)<thresh);
result1_3(r+1:n_rows-r,r+1:n_cols-r)=(result_3(r+1:n_rows-r,r+1:n_cols-r)<thresh);
% clear result_1 result_2 result_3
% result1=result1_1;
result1=((result1_1+result1_2+result1_3)>=2);

% [result_k1 result_k5 result_k15 result_k25 result_k35]=GetMask_KNN(dif1,weight,PA,xtarg,xback);
% tic
% result_k1=GetMask_NN(dif1,weight,PA,xtarg,xback);
% toc
% result_k1=logical(result_k1);
% result_k5=logical(result_k5);
% result_k15=logical(result_k15);
% result_k25=logical(result_k25);
% result_k35=logical(result_k35);

disp('Calculating the detecting rate...');

%result1 is the judgement result from ML.
%We throw out those connected areas which are smaller than min_region. Then
%we get result2.
clear result2;
result2=bwareaopen(result1,min_target,4);

%
% [myL mynum1]=bwlabeln(result1);
% [myL mynum2]=bwlabeln(result2);
% mynum1
% mynum2
%

%label the connected areas in result2
clear L;
[L num]=bwlabeln(result2);

%Calculate the false alarm rate and detect rate
nDetected=num;
nTrueTarg=0;
nFalseAlarm=0;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Evaluate performance by pixels
pDetected=sum(sum(result2));  %total detected pixels;
pTrueTarg=0;    %initial
pFalseAlarm=0;  %values
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
cord_row=zeros(1,num);
cord_col=zeros(1,num);
ncord=zeros(1,num);
[lm ln]=size(L);
for i=1:lm
    for j=1:ln
        if L(i,j)==0
            continue;
        else
            ncord(L(i,j))=ncord(L(i,j))+1;
            cord_row(L(i,j))=cord_row(L(i,j))+i;
            cord_col(L(i,j))=cord_col(L(i,j))+j;
        end
    end
end

for i=1:num
    hasmatch=0;
    cord_row(i)=round(cord_row(i)/ncord(i));
    cord_col(i)=round(cord_col(i)/ncord(i));
    for j=1:deploy.N_targets
        row=round(north_max-deploy.N_coord(j)+1);
        col=round(deploy.E_coord(j)-east_min+1);
        if sqrt((cord_row(i)-row)^2+(cord_col(i)-col)^2)<=rad
            nTrueTarg=nTrueTarg+1;
            pTrueTarg=pTrueTarg+ncord(i);
            hasmatch=1;
            break;
        end
    end
    if hasmatch == 0
        nFalseAlarm=nFalseAlarm+1;
        pFalseAlarm=pFalseAlarm+ncord(i);
    end
end
if pTrueTarg+pFalseAlarm ~= pDetected
    disp('True detected pixels plus false alarm pixels does not equal to total detections!');
    return;
end
% ShowMarks(result2,deploy);
disp('Before false alarm screening:')
disp(sprintf('Number of detected targets:%d',nDetected));
disp(sprintf('Number of detected true targets:%d',nTrueTarg));
disp(sprintf('Number of False Alarms:%d',nFalseAlarm));