find longest line in image in matlab

To find the longest line in an image using MATLAB, follow these steps:

  1. Read the image into MATLAB using the imread function.
main.m
img = imread('image.jpg');
27 chars
2 lines
  1. Enhance the image to improve the visibility of edges using techniques like contrast stretching or histogram equalization.
main.m
img_enhanced = imadjust(img);
30 chars
2 lines
  1. Detect edges in the enhanced image using edge detection functions like edge or edgeSegment.
main.m
edges = edge(img_enhanced, 'Canny');
37 chars
2 lines
  1. Find straight line segments in the image using a function like houghlines or line in the Hough transform.
main.m
[H,T,R] = hough(edges);
P  = houghpeaks(H,5,'threshold',ceil(0.3*max(H(:))));
lines = houghlines(edges,T,R,P,'FillGap',5,'MinLength',10);
138 chars
4 lines
  1. Iterate through all the detected line segments and calculate their length. Keep track of the line segment with the longest length.
main.m
max_len = 0;

for k = 1:length(lines)
   xy = [lines(k).point1; lines(k).point2];
   len = norm(lines(k).point1 - lines(k).point2);
   if ( len > max_len)
      max_len = len;
      xy_long = xy;
   end
end
207 chars
11 lines
  1. Visualize the longest line segment on the original image using the line function.
main.m
imshow(img);
hold on;
plot(xy_long(:,1),xy_long(:,2),'LineWidth',2,'Color','red');
83 chars
4 lines

This will display the original image with the longest line segment highlighted in red.

gistlibby LogSnag