

im = imread('ork.jpg'); % T = 30
% im = imread('cof2.jpg'); % T = 30
% im = imread('sandman.jpg');  % T=100 is okay
% im = imread('cthulhu.jpg'); % T = 30
% im = imread('cthulhu2.jpg'); % T = 70

clear s
clear q

im = sum(im,3);
im = im/max(im(:));

x = size(im,2);
y = size(im,1);

for i=1:(x/2)
    for j=1:(y/2)
        hp(i,j) = 1./(1+exp(-((i-(x/4))+(j-(y/4)))/((x+y)/20)));
    end
end

ft = fft2(im);

s(1,:)=std(abs(ft));
q(1)=sum(std(abs(ft)));

clear im

fc=ft.*(abs(ft)>1);
ift = ifft2(fc);
s(2,:)=std(abs(fc));
q(2)=sum(std(abs(fc)));
%subplot(2,3,1);
%imshow(ift);
%pause;

for T=1:20
    fc=ft.*(abs(ft)>T*10);
    ift = ifft2(fc);
    s(T+2,:)=std(abs(fc));
    q(T+2)=sum(std(abs(fc)));
    if ((q(1) - q(T+2))/q(1) > 0.05)
        if (T > 1)
            fprintf('Best threshold is: %d \n',(T-1)*10);break;
        else
            fprintf('Best threshold is: 1 \n');break;
        end
    end
%    subplot(2,3,T+1);
%    imshow(ift);
%    pause;
end
