%% Script de détection en batch du trait de côte d'une série de photos
% Thomas Dewez Avril 2008

function outmask = detect_wetdry2(inmask, photo)

tic
%% Code original
Mask = inmask;

%% Chargement des images sources 
I = photo;

%% Conversion en HSV attention cette procédure est très lourde
%C=rgb2hsv(I);

%% Calcul des seuils critiques sur les bandes Bleue, Hue, Saturation et Value
% Seuil arbitraire sur la bande bleue
%bc0 = 135; 

% Calcul des paramètres sur B H S V
% B_mean = mean2(I(:,:,3));
% H_mean = mean2(C(:,:,1)); H_std = std2(C(:,:,1));
% S_mean = mean2(C(:,:,2)); S_std = std2(C(:,:,2));
% V_mean = mean2(C(:,:,3)); V_std = std2(C(:,:,3));

% Seuil sur H S V - détermination empirique du script de Déborah Idier
% Hc = H_mean + 0.5 * H_std /(1.5*H_mean);
% Sc = S_mean - 0.5 * S_std /(5*S_mean);
% Vc = V_mean - 1.2 * V_std /(1.6 * V_mean);
% 
%clear H_mean H_std S_mean S_std V_mean V_std;

%% Masquage de la zone candidate
A = zeros(size(I,1),size(I,2));
Rouge = zeros(size(I,1),size(I,2));
Vert = zeros(size(I,1),size(I,2));
Bleu = zeros(size(I,1),size(I,2));
Rouge = double(I(:,:,1));
Vert = double(I(:,:,2));
Bleu = double(I(:,:,3));
Ratio=Rouge./max(Bleu,1);

[counts,x]=imhist(Ratio);
clear K
K=zeros(size(counts));
M=zeros(size(counts));
for i = 11:(length(counts)-11)
 
K(i) = min(counts(i-10:i+10));
M(i) = max(counts(i-10:i+10));

end
L=ones(size(counts));
P=ones(size(counts));

L(find(K - counts == 0))=0;
P(find(M - counts == 0))=0;

indice_seuil_L=find(L==0);
indice_seuil_P=find(P==0);

indice_seuil_L=indice_seuil_L(end);
if indice_seuil_P(end)>indice_seuil_L
    indice_seuil_Pic2=indice_seuil_P(end);
    indice_seuil_Pic1=indice_seuil_P(end-1);
elseif indice_seuil_P(end)<indice_seuil_L
    indice_seuil_Pic2=length(x);
    indice_seuil_Pic1=indice_seuil_P(end);
end

seuil=x(indice_seuil_L)

seuil_moins=seuil-(seuil-x(indice_seuil_Pic1))/1.05
seuil_plus=seuil+(x(indice_seuil_Pic2)-seuil)/3

test=gradient(Ratio);
%if B_mean > bc0
%    A(find(I(:,:,3) > bc0 & C(:,:,1)< Hc & C(:,:,3) > Vc & Mask(:,:,1) > 0)) = 1;
%else
%    A(find(C(:,:,1) < Hc & C(:,:,2)> Sc & C(:,:,3) > Vc & Mask(:,:,1) > 0)) = 1; 
%end
%A(find(Ratio(:,:,1)>0.7 & Ratio(:,:,1)<0.92 & Mask(:,:,1) > 0)) =1;

% A(find(Ratio(:,:,1)>seuil_moins & Ratio(:,:,1)<seuil_plus & Mask(:,:,1) > 0)) =1;

for i = 1:size(I,1)
A(i,find(test(i,:)==min(test(i,:)),1,'last'))=1;
end
outmask = A;

%% A effacer

%save('mask_31.mat', 'A');
%imwrite(A, 'masque_31.tif', 'tif');

time_ratio=toc
