linedetec.m

来自「这是一个使用hough变换来实现一副图像中直线检测的代码,比较高效而且检测效果很」· M 代码 · 共 41 行

M
41
字号
I  = imread('test10.jpg');
rotI = rgb2gray(I);
[x,y,z] = size(I);
% Edge detection by using canny
BW = edge(rotI,'canny');
% Classic hough transform
[H,T,R] = hough(BW);
% ?? houghpeaks, how to set the max peak number ??
P  = houghpeaks(H,20,'threshold',ceil(0.3*max(H(:))));
% Find lines and plot them

%                   FillGap
% If the distance between two line segments is less than FillGap
% Then merge the two lines to one single line

%                   MinLength
% If the length of certain line segment is short than MinLength
% Then delete this line
lines = houghlines(BW,T,R,P,'FillGap',10,'MinLength',30);

% Show the line detection result in the same figure 
% of the original image
figure, imshow(rotI), 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
% Highlight the longest line segment
plot(xy_long(:,1),xy_long(:,2),'LineWidth',2,'Color','cyan');

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?