%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%        Proyecto final de carrera         %%%
%%%   - Francisco Cruz Fernandez             %%%
%%%   - Uppsala universitet                  %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


%I0 es la imagen a segmentar.
%La idea es aplicar el método de Otsu por cuadrantes para compensar la mala
%iluminación de ciertas partes.


%%%% PROBLEMA DE RAYAS EN LOS BORDES DE LOS CUADRANTES!!!!!



%Resaltarlos un poco antes

resaltar;

%%% MÉTODO DE OTSU LOCAL A 9 SECCIONES


Im = res;

Iaux = uint8(zeros(768,1024));


for i=1:1024
    for j=1:768
        Iaux(j,i)=Im(j,i);
    end
end

A = Iaux;

        
for i=1025:2048
    for j=1:768
        Iaux(j,i-1024)=Im(j,i);
    end
end

B = Iaux;

for i=2049:3072
    for j=1:768
        Iaux(j,i-2048)=Im(j,i);
    end
end

C = Iaux;

for i=1:1024
    for j=769:1536
        Iaux(j-768,i)=Im(j,i);
    end
end

D = Iaux;

for i=1025:2048
    for j=769:1536
        Iaux(j-768,i-1024)=Im(j,i);
    end
end

E = Iaux;

for i=2049:3072
    for j=769:1536
        Iaux(j-768,i-2048)=Im(j,i);
    end
end

F = Iaux;

for i=1:1024
    for j=1537:2304
        Iaux(j-1536,i)=Im(j,i);
    end
end

G = Iaux;

for i=1025:2048
    for j=1537:2304
        Iaux(j-1536,i-1024)=Im(j,i);
    end
end

H = Iaux;

for i=2049:3072
    for j=1537:2304
        Iaux(j-1536,i-2048)=Im(j,i);
    end
end

I = Iaux;



level0 = graythresh(A);
level1 = graythresh(B);
level2 = graythresh(C);
level3 = graythresh(D);
level4 = graythresh(E);
level5 = graythresh(F);
level6 = graythresh(G);
level7 = graythresh(H);
level8 = graythresh(I);

level2 = 0.80; %To avoid the bad result;

BW0 = im2bw(A,level0);
BW1 = im2bw(B,level1);
BW2 = im2bw(C,level2);
BW3 = im2bw(D,level3);
BW4 = im2bw(E,level4);
BW5 = im2bw(F,level5);
BW6 = im2bw(G,level6);
BW7 = im2bw(H,level7);
BW8 = im2bw(I,level8);

total = [BW0 BW1 BW2;BW3 BW4 BW5;BW6 BW7 BW8];

%Normal

level = graythresh(res);
BW = im2bw(res,level);

%imtool(BW);
%imtool(total);

