% dip10_2_HoughTransform       17oct16   14nov19
% it.mathworks.com/help/images/hough-transform.html

clear all;

 BW = zeros(100,100);     % test segments
 x = 30:60; y = round(.3*x+23);  BW(sub2ind(size(BW),x,y))=1;
% x = 80:90; y = round(.3*x+23);  BW(sub2ind(size(BW),x,y))=1;
% x = 40:60; y = round(.3*x+63);  BW(sub2ind(size(BW),x,y))=1;
% x = 2:98;  y = round(-.2*x+21);  BW(sub2ind(size(BW),x,y))=1;

I = imread('circuit.tif');
I = imrotate(I,27,'crop');
figure(1); imshow(I); pause();
BW = edge(I,'canny');

figure(1); imshow(BW); pause(.1);

[H,theta,rho] = hough(BW,'RhoResolution',1,'Theta',-90:1:89); % default params
% [H,theta,rho] = hough(BW,'RhoResolution',.2,'Theta',-90:.2:89);

figure(2); imshow(imadjust(mat2gray(H)),[],'XData',theta,'YData',rho);
xlabel('\theta (degrees)');  ylabel('\rho');  hold on
pause(.1);

P = houghpeaks(H,10,'threshold',ceil(0.3*max(H(:))));  % NumPeaks=10 max
% P = houghpeaks(H,100,'threshold',ceil(0.1*max(H(:))));  % 100 peaks, low threshold
x = theta(P(:,2));
y = rho(P(:,1));
figure(2); plot(x,y,'o','color','blue','MarkerFaceColor','blue');
hold off;

 lines = houghlines(BW,theta,rho,P,'FillGap',1,'MinLength',1);
 lines = houghlines(BW,theta,rho,P,'FillGap',5,'MinLength',40);
 lines = houghlines(BW,theta,rho,P,'FillGap',20,'MinLength',40); % default params

figure(3), imshow(BW), hold on
max_len = 0;
for k = 1:length(lines)
   xy = [lines(k).point1; lines(k).point2];
   plot(xy(:,1),xy(:,2),'LineWidth',2,'Color','blue');
end
hold off;       % note fragmented lines and errors

return