function [im2] = fenceDetCC(im, R, G, B , NOP, windSize , treshold )

[m, n, ~] = size(im);
wSize = windSize  * windSize ;
hwSize = floor(windSize/2);

SNOP = NOP * wSize;
k = 1/SNOP;
mewR = sum(R)/SNOP;
mewG = sum(G)/SNOP;
mewB = sum(B)/SNOP;

Srr = k*sum((R-mewR).*(R-mewR));
Srg = k*sum((R-mewR).*(G-mewG));
Srb = k*sum((R-mewR).*(B-mewB));

Sgr = k*sum((G-mewG).*(R-mewR));
Sgg = k*sum((G-mewG).*(G-mewG));
Sgb = k*sum((G-mewG).*(B-mewB));

Sbr = k*sum((B-mewB).*(R-mewR));
Sbg = k*sum((B-mewB).*(G-mewG));
Sbb = k*sum((B-mewB).*(B-mewB));

Sigma = [Srr Srg Srb;
        Sgr Sgg Sgb;
        Sbr Sbg Sbb];
    
iSigma = inv(Sigma);

for i=1:m
    for j=1:n
        cR = double(im(i,j,1));   %Current color
        cG = double(im(i,j,2));
        cB = double(im(i,j,3));
        A = [cR - mewR;
            cG - mewG;
            cB - mewB];
        %         d(i,j) = uint8(A'*iSigma*A);
        d = uint8(A'*iSigma*A);
        if(d<treshold)
            im(i,j,:) = 0;
        end
    end
end

%  For dilation purpose, copy as binary
im2 = zeros(m,n);
indx = find(im(:,:,1) == 0);
im2(indx) = 1;

end
