Search code examples
matlabimage-processinghough-transform

Hough transform in MATLAB


Does anyone know how to use the Hough transform to detect the strongest lines in the binary image:

A = zeros(7,7);
A([6 10 18 24 36 38 41]) = 1;

Using the (rho; theta) format with theta in steps of 45° from -45° to 90°. And how do I show the accumulator array in MATLAB as well.

Any help or hints please?

Thank you!


Solution

  • If you have access to the Image Processing Toolbox, you can use the functions HOUGH, HOUGHPEAKS, and HOUGHLINES:

    %# your binary image
    BW = false(7,7);
    BW([6 10 18 24 36 38 41]) = true;
    
    %# hough transform, detect peaks, then get lines segments
    [H T R] = hough(BW);
    P  = houghpeaks(H, 4);
    lines = houghlines(BW, T, R, P, 'MinLength',2);
    
    %# show accumulator matrix and peaks
    imshow(H./max(H(:)), [], 'XData',T, 'YData',R), hold on
    plot(T(P(:,2)), R(P(:,1)), 'gs', 'LineWidth',2);
    xlabel('\theta'), ylabel('\rho')
    axis on, axis normal
    colormap(hot), colorbar
    
    %# overlay detected lines over image
    figure, imshow(BW), hold on
    for k = 1:length(lines)
        xy = [lines(k).point1; lines(k).point2];
        plot(xy(:,1), xy(:,2), 'g.-', 'LineWidth',2);
    end
    hold off
    

    hough lines