Hough Transform
这Image Processing Toolbox™ supports functions that enable you to use the Hough transform to detect lines in an image.
这hough
function implements the Standard Hough Transform (SHT). The Hough transform is designed to detect lines, using the parametric representation of a line:
ρ= x*cos(theta) + y*sin(theta)
这variableρ
is the distance from the origin to the line along a vector perpendicular to the line.theta
是X轴和该向量之间的角度。这hough
function generates a parameter space matrix whose rows and columns correspond to theseρ
和theta
values, respectively.
After you compute the Hough transform, you can use thehoughpeaks
function to find peak values in the parameter space. These peaks represent potential lines in the input image.
After you identify the peaks in the Hough transform, you can use thehoughlines
function to find the endpoints of the line segments corresponding to peaks in the Hough transform. This function automatically fills in small gaps in the line segments.
Detect Lines in Images Using Hough
This example shows how to detect lines in an image using the Hough
transform.
在工作区中读取图像,并使此示例更具说明性,请旋转图像。显示图像。
I = imread('电路.tif'); rotI = imrotate(I,33,'庄稼'); imshow(rotI)
使用图像中的边缘edge
function.
BW = edge(rotI,'canny'); imshow(BW);
Compute the Hough transform of the binary image returned byedge
.
[H,theta,rho] = hough(BW);
Display the transform,H
, returned by thehough
function.
figure imshow(imadjust(rescale(H)),[],...“XData”,theta,...'YData',rho,...'InitialMagnification','fit'); xlabel('\theta (degrees)')ylabel('\rho') axis上axisnormalhold上colormap(gca,hot)
Find the peaks in the Hough transform matrix,H
, using thehoughpeaks
function.
P = houghpeaks(H,5,'threshold',ceil(0.3*max(H(:))));
Superimpose a plot on the image of the transform that identifies the peaks.
x = theta(P(:,2)); y = rho(P(:,1)); plot(x,y,'s','color','black');
Find lines in the image using thehoughlines
function.
lines = houghlines(BW,theta,rho,P,'FillGap',5,'MinLength',7);
Create a plot that displays the original image with the lines superimposed on it.
figure, imshow(rotI), hold上max_len = 0;fork = 1:length(lines) xy = [lines(k).point1; lines(k).point2]; plot(xy(:,1),xy(:,2),'LineWidth',2,'Color','green');% Plot beginnings and ends of linesplot(xy(1,1),xy(1,2),'x','LineWidth',2,'Color','yellow'); plot(xy(2,1),xy(2,2),'x','LineWidth',2,'Color',“红色”);% Determine the endpoints of the longest line segmentlen = norm(lines(k).point1 - lines(k).point2);if( len > max_len) max_len = len; xy_long = xy;endend% highlight the longest line segmentplot(xy_long(:,1),xy_long(:,2),'LineWidth',2,'Color',“红色”);