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

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

function[]=Hough(img,edgeThreshold,houghThreshold)


dimens=size(img);
height=dimens(1);
width=dimens(2);

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

for x=2:(width-1)
   for y=2:(height-1)
      gx=(img(y,x-1)*-2+img(y,x+1)*2+img(y-1,x-1)*-1+img(y-1,x+1)+img(y+1,x-1)*-1+img(y+1,x+1))/8;
      gy=(img(y-1,x)*2+img(y+1,x)*-2+img(y-1,x-1)+img(y-1,x+1)+img(y+1,x-1)*-1+img(y+1,x+1)*-1)/8;
      
      gradient=sqrt(gx*gx+gy*gy);
      
      if gradient>edgeThreshold
         
         for theta=0:0.01:(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(accumulator);    
colorbar;

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

figure;
imagesc(transformed);    
colorbar;         