How can apply the Hough transform to detect lines in an images?

1 回表示 (過去 30 日間)
sonia carole
sonia carole 2016 年 2 月 2 日
回答済み: Aniket 2025 年 4 月 10 日
%% Find lines and plot them lines = houghlines(imEdge,T,R,P,'FillGap',30,'MinLength',15); figure, imshow(im), 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 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');
% 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
%imclearborder
% highlight the longest line segment
plot(xy_long(:,1),xy_long(:,2),'LineWidth',2,'Col

回答 (1 件)

Aniket
Aniket 2025 年 4 月 10 日
The code you have provided uses the peaks from the Hough Transform to extract lines using houghlines and then plots all the detected lines. Please find below a brief explation to detect edges and compute the Hough Transform:
  • Convert image to grayscale
im = imread('image.jpeg');
gray = rgb2gray(im);
  • Detect Edges
imEdge = edge(gray, 'Canny');
  • Compute the Hough Transform
[H, T, R] = hough(imEdge);
  • Identify peaks in Hough Transform
P = houghpeaks(H, 10, 'Threshold', ceil(0.3 * max(H(:))));
  • Extract Lines and plot them: This is same as the code provided by you.
lines = houghlines(imEdge, T, R, P, 'FillGap', 30, 'MinLength', 15);
figure, imshow(im), 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 endpoints
plot(xy(1,1), xy(1,2), 'x', 'LineWidth', 2, 'Color', 'yellow');
plot(xy(2,1), xy(2,2), 'x', 'LineWidth', 2, 'Color', 'red');
% Keep track of the longest line
len = norm(lines(k).point1 - lines(k).point2);
if len > max_len
max_len = len;
xy_long = xy;
end
end
% Highlight the longest line
plot(xy_long(:,1), xy_long(:,2), 'LineWidth', 2, 'Color', 'blue');
You may modify the code based on your requirements (Horizontal lines/ removing short lines etc.)
You may also use Hough Transform block from Computer Vision Toolbox which inputs an image and returns the Hough Transform: https://www.mathworks.com/help/vision/ref/houghtransform.html
I hope this helps!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by