par = imread('par.jpg');
par_gray = rgb2gray(par);
imshow(par_gray);

H = fspecial('average', 5);
par_smooth = imfilter(par_gray, H, 'replicate');
par_edge = edge(par_smooth, 'canny');
imshow(par_edge);

imshow(par_edge);
[HM, theta, rho] = hough(par_edge);
peaks = houghpeaks(HM, 15);
lines = houghlines(par_edge, theta, rho, peaks);


figure, imshow(par_gray), hold on;

for k = 1:length(lines)
   xy = [lines(k).point1; lines(k).point2];
   plot(xy(:,1),xy(:,2),'LineWidth',3,'Color','green');

   % Plot beginnings and ends of lines
   plot(xy(1,1),xy(1,2),'x','LineWidth',3,'Color','yellow');
   plot(xy(2,1),xy(2,2),'x','LineWidth',3,'Color','red');

   % Determine the endpoints of the longest line segment
   len = norm(lines(k).point1 - lines(k).point2);
   if ( len > max_len)
      max_len = len;
      xy_long = xy;
   end
end

% highlight the longest line segment
plot(xy_long(:,1),xy_long(:,2),'LineWidth',2,'Color','red');

