%================================================= 
% Calculation of the co-occurence matrix
% for agles 0, 45 and 90
% Aleksandra Pizurica, TELIN, RUG, 2003.
%=================================================

function C=cooccurence(A,Angle,distance);

[M,N]=size(A);
A=A+1;
MIN=min(min(A));
MAX=max(max(A));

if(MIN<0 | MAX>256)
    Error='Input image must be grayscale 0-255'
    break;
end
if((Angle~=0)&(Angle~=45)&(Angle~=90))
    Error='Invalid_angle'
    break;
end
d=round(distance);
if(distance<0 | distance >M | distance>N)
    Error='Invalid_distance (negative or larger than image size)'
    break;
end



%===================================================================
% initialize co-occurence matrix
C=zeros(256,256);

% Calculate the co-occurence matrix for Angle=0
if (Angle==0)
  for i=1:M
      for j=1:(N-d)
          C(A(i,j),A(i,j+d))=C(A(i,j),A(i,j+d))+1;
      end
  end
end

% Calculate the co-occurence matrix for Angle=90
if (Angle==90)
  for j=1:N
      for i=1:(M-d)
          C(A(i,j),A(i+d,j))=C(A(i,j),A(i+d,j))+1;
      end
  end
end

% Calculate the co-occurence matrix for Angle=45
if (Angle==45)
    for i=1:(M-d)
       for j=1:(N-d)
          C(A(i,j),A(i+d,j+d))=C(A(i,j),A(i+d,j+d))+1;
       end
    end 
end


% Normalize the cooccurence matrix
C=C/(M*N);

%figure
%imagesc(C);
%colormap(jet);
%title('Co-occurence matrix');
