1.Hough Transform 的算法思想
在直角坐标系和極坐标系中,點、線是對偶關系。
即直角坐标系中的點是極坐标系中的線,直角坐标系中的線是極坐标系中的點。反之也成立。
如下圖所示,想要檢測圖像中的直線,可以轉化為檢測極坐标系中的點 (θ,r) 。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICMwUDNzUzMwETNxQDM2EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
2.Hough空間的表示
如下圖所示,圖像中直線的表示,由斜率和截距表示,而極坐标中用 (θ,r) 表示,并且存在下式關系:
r=cos(θ)⋅x+sin(θ)⋅y
對于點 (x0,y0) ,代入上式,在極坐标中就是一條線(很多對 (θ,r) 點): r=cos(θ)⋅x0+sin(θ)⋅y0
r,θ 就是一對Hough空間的變量表示。
旋轉的 θ 不容易表示,若将 r,θ 看成直角坐标空間。一個點 (x0,y0) , 就是一個正弦曲線。
r=cos(θ)⋅x0+sin(θ)⋅y0
如下圖所示,左圖直角坐标系中的一個點,對應于右圖 r -θ 空間的一條正弦曲線。
如下圖,直角坐标系中的多個點,對應于 r -θ 空間的多條正弦曲線。
直角坐标系的三點共線,對應于 r -θ 空間的多線共點。
是以,我們可以通過檢測 r -θ 空間的交集點,來檢測原始空間的線段。
接下來,就是要考慮 将 r,θ 離散化,形成離散化的Hough空間,類似于一個矩陣/圖像(如下圖),用于統計交集點的個數。
3.Hough變換代碼分析
以下是使用Matlab進行直線檢測的代碼。
Hough Transform
首先預處理,轉為二值圖像:
I = imread('road.jpg');
I = rgb2gray(I);
BW = edge(I,'canny');
然後進行霍夫變換:
[H,T,R] = hough(BW,'RhoResolution',,'Theta',-::);
imshow(H,[],'XData',T,'YData',R,'InitialMagnification','fit');
xlabel('\theta'), ylabel('\rho');
axis on, axis normal, hold on;
檢測hough域極值點
P = houghpeaks(H,,'threshold',ceil(*max(H(:))));
x = T(P(:,));
y = R(P(:,));
plot(x,y,'s','color','white');
檢測直線
% Find lines and plot them
lines = houghlines(BW,T,R,P,'FillGap',,'MinLength',);
figure, imshow(I), hold on
max_len = ;
for k = :length(lines)
xy = [lines(k).point1; lines(k).point2];
plot(xy(:,),xy(:,),'LineWidth',,'Color','green');
% plot beginnings and ends of lines
plot(xy(,),xy(,),'x','LineWidth',,'Color','yellow');
plot(xy(,),xy(,),'x','LineWidth',,'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(:,),xy_long(:,),'LineWidth',,'Color','cyan');
實驗結果
r -θ 空間及前50個極值點:
最終車道直線檢測結果:
[注] 所有的代碼可以在此處免費下載下傳:http://download.csdn.net/detail/ws_20100/9492054