1

I am trying to find all straight lines (vertical or diagonal) in an image using Matlab. The problem is that it include any line even horizontal lines. this is my code. How can I detect all straight lines in the image below (they can be between 45 to 115 degrees)?

function [linesnum, avg]= hh(inp_file,tresh)

I  = imread(inp_file);

BW = edge(I,'canny');
% [H,T,R] = hough(BW,'Theta', 45:0.5:90); % it has no efect

[H,T,R] = hough(BW);
P  = houghpeaks(H,300,'threshold',ceil(0.3*max(H(:))));   

lines = houghlines(BW,T,R,P,'FillGap',10,'MinLength',30);

if (do_plot)
    figure, imshow(I), hold on
    x = T(P(:,2));
    y = R(P(:,1));
    plot(x,y,'s','color','black');
end
max_len = 0;
linesnum = 0;
sumLen = 0;

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

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

    len = norm(lines(k).point1 - lines(k).point2);
    sumLen = sumLen + len;

    linesnum = linesnum +1;

end   
avg = sumLen / linesnum;
end

enter image description here

This is a sample image:

enter image description here


There is a similar question for grid detection but it seems in that question they rely on the holes of the grid to detect the grid pattern and its orientation, while my input is different.

Community
  • 1
  • 1
Ahmad
  • 8,811
  • 11
  • 76
  • 141

1 Answers1

0

After detecting straight lines using hough transform, you can measure the angle of each line and if it was in the range select it.

 % after extracting straight lines using Haugh transform.
 for k = 1:length(lines)

    xy = [lines(k).point1; lines(k).point2];

    deltaY = xy(2,2) - xy(1,2);
    deltaX = xy(2,1) - xy(1,1);
    % calculate the angle of line
    angle = atan2(deltaY, deltaX) * 180 / pi;
    if (angle > 45 && angle < 115)

        plot(xy(:,1),xy(:,2),'LineWidth',2,'Color','green');

        % Plot beginnings and ends of lines
        plot(xy(1,1),xy(1,2),'x','LineWidth',2,'Color','yellow');
        plot(xy(2,1),xy(2,2),'x','LineWidth',2,'Color','red');        
    end
end
Ahmad
  • 8,811
  • 11
  • 76
  • 141