我试图使用Matlab找到图像中的所有直线(垂直或对角线)。问题是它包括任何线甚至水平线。 这是我的代码。如何检测下图中的所有直线(它们可以在45到115度之间)?
function [linesnum, avg]= hh(inp_file,tresh)
I = imread(inp_file);
BW = edge(I,'canny');
% [H,T,R] = hough(BW,'Theta', 45:0.5:90); % it has no efect
[H,T,R] = hough(BW);
P = houghpeaks(H,300,'threshold',ceil(0.3*max(H(:))));
lines = houghlines(BW,T,R,P,'FillGap',10,'MinLength',30);
if (do_plot)
figure, imshow(I), hold on
x = T(P(:,2));
y = R(P(:,1));
plot(x,y,'s','color','black');
end
max_len = 0;
linesnum = 0;
sumLen = 0;
for k = 1:length(lines)
xy = [lines(k).point1; lines(k).point2];
vert = xy(1,1)==xy(2,1);
if (do_plot)
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');
end
len = norm(lines(k).point1 - lines(k).point2);
sumLen = sumLen + len;
linesnum = linesnum +1;
end
avg = sumLen / linesnum;
end
这是一张示例图片:
网格检测有类似的question,但在这个问题中,他们依靠网格的孔来检测网格图案及其方向,而我的输入则不同。
答案 0 :(得分:0)
使用霍夫变换检测直线后,您可以测量每条线的角度,如果它在范围内,则选择它。
% after extracting straight lines using Haugh transform.
for k = 1:length(lines)
xy = [lines(k).point1; lines(k).point2];
deltaY = xy(2,2) - xy(1,2);
deltaX = xy(2,1) - xy(1,1);
% calculate the angle of line
angle = atan2(deltaY, deltaX) * 180 / pi;
if (angle > 45 && angle < 115)
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');
end
end