先使用上文介绍的Prewitt算子将输入的图像边缘化处理,再使用霍夫变换检测直线。 其中使用到了matlab的hough,houghpeaks,houghlines等函数.
寻找最长直线将每个两个点坐标遍历一遍记录最长距离的两个点并输出。
mian.m
% Find the longest line segment based on Hough transform.
[x, y] = mylineextraction(f);
% Plot the line in the image
figure; imshow(Im, [min(min(Im)) max(max(Im))]), hold on
plot([x(1) y(1)], [x(2) y(2)],'LineWidth',2,'Color','blue');
plot(x(1),x(2),'x','LineWidth',2,'Color','red');
plot(y(1),y(2),'x','LineWidth',2,'Color','red');
hold offmylineextraction.m
function [bp, ep] = mylineextraction(BW)
% The function extracts the longest line segment from the given binary image
% Input parameter:
% BW = A binary image.
%
% Output parameters:
% [bp, ep] = beginning and end points of the longest line found
% in the image.
[n, m] = size(BW);
[H,T,R] = hough(BW);
P = houghpeaks(H,8,'threshold',ceil(0.2*max(H(:))));
lines= houghlines(BW,T,R,P,'FillGap',20,'MinLength',7);
maxLength = 0;
for k = 1:length(lines)
xy = [lines(k).point1; lines(k).point2];
if (((xy(1,1) - xy(2,1))^2 + (xy(1,2) - xy(2,2))^2) > maxLength)
maxLength = (xy(1,1) - xy(2,1))^2 + (xy(1,2) - xy(2,2))^2;
bp = xy(1,:);
ep = xy(2,:);
end
end 输入图片

输出图片 已找到图片中最长的直线
