%http://www.mathworks.com/matlabcentral/fileexchange/14995-anisotropic-diffusion--perona---malik-

function TAI()
    im=imread('malaria.jpg');
    noyau=im(:,:,2)<70;
    %imshow(noyau);
    %figure;
    im2=fermeture(noyau, 5);
    %imshow(im2);
    %L=bwlabel(noyau);
    %max(max(L))
    %figure;
    im3=erosion(im2, 2);
    %imshow(im3);
    max(max(bwlabel(im3)))
    
    p=uint8(im(:,:,1)<205);
    I=zeros(size(im), 'uint8');
    I(:,:,1)=im(:,:,1).*p;
    I(:,:,2)=im(:,:,2).*p;
    I(:,:,3)=im(:,:,3).*p;
    
    
    imshow(I);
end

function res = dilatation( I, rayon)
    [m, n, can] = size(I);      %m=nb lignes, n=nb colonnes, can=nb canaux
        if(can > 1)
            I = rgb2gray(I);          %dans le cas d'une image couleur, la transformer en NG
        end
    res=zeros(m,n);
    for i=rayon+1:m-1-rayon
        for j=rayon+1:n-1-rayon
            if(I(i, j)>0)
                res(i-rayon:i+rayon, j-rayon:j+rayon)=1;
            end
        end
	end
end


function res = erosion( I, rayon)
    [m, n] = size(I);      %m=nb lignes, n=nb colonnes, can=nb canaux
    res=zeros(m, n);
    for i=rayon+1:m-1-rayon
        for j=rayon+1:n-1-rayon
            if(I(i, j)>0)
                res(i, j)=min(min(I(i-rayon:i+rayon, j-rayon:j+rayon)));
            end
        end
    end;
end

function res = fermeture( I, rayon)
    [m, n, can] = size(I);      %m=nb lignes, n=nb colonnes, can=nb canaux
    if(can > 1)
        I = rgb2gray(I);          %dans le cas d'une image couleur, la transformer en NG
    end
    dil=dilatation(I, rayon);
    res=erosion(dil, rayon);
end
