%HOUGH TRANSFORM****************************************

%Hough Line Detection
%Arguments input image,edge threshold,Hough threshold

function[]=Hough(img,edgeThreshold)


dimens=size(img);
height=dimens(1);
width=dimens(2);
matrixGx=[-1 0 1;-2 0 2;-1 0 1];
matrixGy=[1 2 1;0 0 0;-1 -2 -1];

gradientmatrix=zeros(height,width);
accumulator=zeros(height,width);
transformed=zeros(height,width);

for x=2:(width-1)
   for y=2:(height-1)
      gx=sum(sum(matrixGx.*img((y-1):(y+1),(x-1):(x+1))))/8;
      gy=sum(sum(matrixGy.*img((y-1):(y+1),(x-1):(x+1))))/8;
      
      gradient=sqrt(gx*gx+gy*gy);
      gradientmatrix(y,x)=gradient;
      
      if gradient>edgeThreshold
         
         for theta=0:((2*pi)/200):(2*pi)
            r=(x*cos(theta))+(y*sin(theta));
            p=uint16((theta*(height/(2*pi))));
            q=uint16(r);
            if p>0 
               if p<=(height)
                  if q>0
                     if q<=(width)
                        accumulator(p,q)=accumulator(p,q)+gradient;
                     end
                  end
               end
            end   
         end
      end
   end
end



figure;
imagesc(gradientmatrix);    
colorbar;

figure;
imagesc(accumulator);    
colorbar;

accMax=max(max(accumulator));
houghThreshold=(accMax/100)*90;

for x=1:width
   for y=1:height
      if accumulator(y,x)>houghThreshold
         for b=1:width
            innards=y/(width/(2*pi));
            a=uint16((x-(b*cos(innards)))/sin(innards));
            if a>0
               if a<=height
                  transformed(a,b)=255;
               end
            end
         end   
         
      end
   end
end

figure;
imagesc(transformed);    
colorbar;         