Main Content

霍夫变换

Image Processing Toolbox™ 支持使您能够使用霍夫变换检测图像中线条的函数。

hough 函数实现标准霍夫变换 (SHT)。霍夫变换设计为使用线条的参数化表示来检测线条:

rho = x*cos(theta) + y*sin(theta)

变量 rho 是沿垂直于线条的向量从原点到线条的距离。theta 是 x 轴与此向量之间的角度。hough 函数生成一个参数空间矩阵,其行和列分别对应于这些 rhotheta 值。

在计算霍夫变换后,您可以使用 houghpeaks 函数来求得参数空间中的峰值。这些峰值表示输入图像中可能存在的线条。

在标识霍夫变换中的峰值后,可以使用 houghlines 函数求得霍夫变换中对应于峰值的线段的端点。此函数自动填充线段中的小间隙。

使用霍夫变换检测图像中的线条

此示例说明如何使用 Hough 变换检测图像中的线条。

将一个图像读入工作区中,为了使此示例更具说明性,请旋转该图像。显示图像。

I = imread('circuit.tif');
rotI = imrotate(I,33,'crop');
imshow(rotI)

使用 edge 函数找到图像中的边缘。

BW = edge(rotI,'canny');
imshow(BW);

计算由 edge 返回的二值图像的霍夫变换。

[H,theta,rho] = hough(BW);

显示由 hough 函数返回的变换 H

figure
imshow(imadjust(rescale(H)),[],...
       'XData',theta,...
       'YData',rho,...
       'InitialMagnification','fit');
xlabel('\theta (degrees)')
ylabel('\rho')
axis on
axis normal 
hold on
colormap(gca,hot)

使用 houghpeaks 函数,在霍夫变换矩阵 H 中找到峰值。

P = houghpeaks(H,5,'threshold',ceil(0.3*max(H(:))));

在标识了峰值的变换图像上叠加一个绘图。

x = theta(P(:,2));
y = rho(P(:,1));
plot(x,y,'s','color','black');

使用 houghlines 函数查找图像中的线条。

lines = houghlines(BW,theta,rho,P,'FillGap',5,'MinLength',7);

创建一个显示原始图像并在其上叠加线条的绘图。

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','red');