find horizontal hough lines in matlab

To find the horizontal hough lines in Matlab, we can follow the following steps:

  1. Read the image we want to work with.
  2. Convert the image to grayscale and perform edge detection using the Canny edge detection algorithm.
  3. Create a Hough transform accumulator using the hough function.
  4. Compute the Hough transform using the houghlines function.
  5. Filter the lines to keep only the ones that are nearly horizontal.
  6. Draw the horizontal lines on the original image.

Here is the example code that demonstrates these steps:

main.m
%% Read the image
I = imread('image.jpg');

%% Convert the image to grayscale
gray = rgb2gray(I);

%% Perform edge detection
edges = edge(gray, 'canny');

%% Create a Hough transform accumulator
[H, theta, rho] = hough(edges);

%% Compute the Hough transform
lines = houghlines(edges, theta, rho, H);

%% Filter the lines to keep only the nearly horizontal ones
horizontalLines = lines(abs([lines.theta]) < 10);

%% Draw the horizontal lines on the original image
figure, imshow(I), hold on
for k = 1:length(horizontalLines)
   xy = [horizontalLines(k).point1; horizontalLines(k).point2];
   plot(xy(:,1),xy(:,2),'LineWidth',2,'Color','green');
end
649 chars
25 lines

Note that in the code above, we filter the lines by checking their theta values. In this case, we keep only the lines that have theta values less than 10 degrees or greater than 170 degrees. You can adjust these values to keep more or fewer lines depending on your specific needs.

gistlibby LogSnag