滤波Hough变换在Matlab中只寻找水平和垂直直线

zour9fqk  于 2022-11-30  发布在  Matlab
关注(0)|答案(2)|浏览(173)

我正在尝试编写一些代码,可以在图像中找到线条,并在找到的线条上画一条红线。我已经设法使用霍夫变换做到了这一点,但我的问题是,我需要它只找到水平和垂直线,而忽略了所有其他斜率的线条。
我想我可以通过查找代码找到的直线的斜率来解决这个问题,并且使用if语句只在水平线和垂直线上显示红线,但是我在如何从找到的点中提取x和y值方面遇到了麻烦。
有人对如何解决这个问题有什么建议吗?
下面是我的代码:

function findlineshv(I)

% Read Image
img = imread(I);

% Convert to black and white because
% edge function only works with BW imgs
bwImage = rgb2gray(img);

% figure(1),imshow(bwImage);

% find edges using edge function
b=edge(bwImage,'sobel');

% show edges
% figure(1),imshow(b);

% compute the Hough transform of the edges found
% by the edge function
[hou,theta,rho] = hough(b);

% define peaks, x and y
peaks = houghpeaks(hou,5,'threshold',ceil(0.3*max(hou(:))));

x = theta(peaks(:,2));
y = rho(peaks(:,1));

lines = houghlines(bwImage,theta,rho,peaks,'FillGap',5,'MinLength',7);

figure, imshow(bwImage), hold on

for k = 1:length(lines)
    xy = [lines(k).point1; lines(k).point2];
    plot(xy(:,1),xy(:,2),'LineWidth',3,'Color','red');
end
puruo6ea

puruo6ea1#

只需在Hough函数中设置所需的theta值即可完成此操作。

start_angle = 80;
end_angle = 100;
theta_resolution = 0.5:

[H,T,R] = hough(b, 'Theta', start_angle:theta_resolution:end_angle);
k2fxgqgv

k2fxgqgv2#

这可以通过使用前面回答的所需θ范围来完成。增加这一点以提及θ范围必须在[-90,90)之内。

  • 对于水平线检测,使用范围-90:-85(根据需要修改限值)
  • 对于垂直线检测,使用范围-3:3(根据需要修改限值)
I  = imread('circuit.tif');I = edge(I,'canny');
    %% Hough Transform based Horizontal line detection
    [H,theta,rho] = hough(I,'Theta',-90:0.5:-85);
    P = houghpeaks(H,5,'threshold',ceil(0.3*max(H(:))));
    lines = houghlines(I,theta,rho,P,'FillGap',5,'MinLength',3);
    figure, imshow(I), 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','red');

按以下方式更改Angular 限制将生成垂直线:

[H,theta,rho] = hough(I,'Theta',-3:0.5:-3);

参考:https://www.mathworks.com/help/images/hough-transform.html

相关问题