% On essaye de trouver le k optimal
%  ratio( IMAGE )

function kopt = ratio(J)
% On prepare le terrain 
% et on affiche l'image originale
%close all;
%figure, imshow(J);
% On cree tous les handles
ed = @edginess;
cons = @byaverage;
n = @norme;
% pour l'image en entier
N = imread(J);

% SEQUENCE BRUITAGE
%N = imnoise(N,'gaussian',0,0.01);
%N = imnoise(N,'poisson');
%N = imnoise(N,'speckle',0.04);
%N = imnoise(N,'salt & pepper',0.02);
%figure, imshow(N);
%M = histeq(M);

% SEQUENCE DEBRUITAGE
%M = medfilt2(M,[3 3]);
N = wiener2(N,[5 5]);
N = im2double(N);
[l,c] = size(N);
% En la divisant en quatre
%N = imcrop(N,[1 1 floor(c/2) floor(l/2)]);
%N = imcrop(N,[floor(c/2)+1 1 floor(c/2) floor(l/2)]);
%N= imcrop(N,[1 floor(l/2)  floor(c/2) floor(l/2)]);
%N = imcrop(N,[floor(c/2)+1 floor(c/2)+1 floor(c/2) floor(l/2)]);
%[l,c] = size(N);

for i = 1:l-1
    for j = 1:c-1
        e(i,j) = feval( ed, N, i, j);
        d(i,j) = feval( cons, N, i, j);
        R(i,j) = e(i,j)*d(i,j);
    end     
end
R;
dim_image = (l-1)*(c-1);
% On etale les valeurs et on les classe:
R2 = R(:);
R3 = sort(R2);
x = zeros([dim_image 1]);
k = 1:dim_image;
x(k) = k;
y = R3(dim_image-(x-1));
dy = diff(R3(dim_image-(x-1)))./diff(x);
xd = x(1:length(x)-1);
% on trace le plot:
%figure, plot(x,y,'b',xd,dy,'r');
figure, semilogx(x,y,'b',xd,dy,'r')


% Ensuite om introduit un seuil et on ne garde
% dans R que les termes superieurs a ce seuil:
%k4 = R3((l-1)*(c-1)-10^4);
%A = [];
%B = [];
%C = [];
%k = R3((l-1)*(c-1)) 
%for i = 1:l-1
 %   for j = 1:c-1
  %      if feval( n, N, i, j) == 0
   %         e(i,j) = feval( ed, N, i, j);
    %        d(i,j) = feval( cons, N ,i, j);
    %else
    %        e(i,j) = feval( ed, N, i, j);
     %       d(i,j) = feval( cons, N ,i, j);
     %end
     %   R(i,j) = e(i,j)*d(i,j);
      %  if R(i,j) > 0.001*k
       %    A(i,j) = 1;
       %else A(i,j) = 0;
       %end
       %end     
       %end
%I_matrice1 = A;

%I_edge1 = im2bw(A);

%figure, imshow(I_edge1);
