overlay lines from hough transform in matlab

To overlay lines detected from the Hough transform onto an image in Matlab, follow these steps:

  1. Read in the image and convert it to grayscale:

    main.m
    img = imread('image.jpg');
    grayImg = rgb2gray(img);
    
    52 chars
    3 lines
  2. Apply edge detection to extract edges from the image:

    main.m
    edgeImg = edge(grayImg, 'canny');
    
    34 chars
    2 lines
  3. Apply the Hough transform to detect lines:

    main.m
    [H,theta,rho] = hough(edgeImg);
    P = houghpeaks(H,5);
    lines = houghlines(edgeImg,theta,rho,P);
    
    94 chars
    4 lines
  4. Overlay the detected lines onto the original image:

    main.m
    figure, imshow(img), 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','green');
    
       % Plot end points
       plot(xy(1,1),xy(1,2),'x','LineWidth',2,'Color','yellow');
       plot(xy(2,1),xy(2,2),'x','LineWidth',2,'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','blue');
    
    590 chars
    21 lines

This will display the original image with the detected lines overlaid in green, and the end points of each line segment highlighted in yellow and red. The longest line segment will be highlighted in blue.

gistlibby LogSnag