霍夫變換(直線檢測)

版權聲明:本文爲博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/wangxiaobei2017/article/details/78062606

霍夫變換對於邊緣檢測來說是一個非常重要的工具,它可以通過連接技術將像素組合成完整的邊緣。主要是通過圖像空間與參數空間的轉換。下面檢測車道線圖片。
霍夫變換的數學思想,將參數空間離散化,建立一個二維數組累加器A(a,b)=0,對每一個圖像座標系中的前景點(x,y),都能在參數空間中算出一組A(a,b),a=0,1,2,3,…,n,遍歷完m個前景點後,生產m*n組A(a,b),統計出現頻率最高的幾個點,就是圖像座標系中的線段(每一個點都是一條線段)

%通過霍夫變換檢測車道線

I1 = imread('chedao.png');
I = rgb2gray(I1);
subplot(2,3,1);
imshow(I1);
subplot(2,3,2);
imshow(I);

%通過Canny算子檢測邊緣
BW = edge(I,'canny');
subplot(2,3,3);
imshow(BW);

%執行霍夫變換 顯示霍夫矩陣
[H,T,R] = hough(BW);
subplot(2,3,4);
imshow(H,[],'XData',T,'YData',R,'InitialMagnification','fit');
xlabel('\theta'),ylabel('\rho');
axis on,axis normal,hold on;

%在霍夫矩陣中找到前五個大於最大值0.3倍的峯值
P = houghpeaks(H,5,'threshold',ceil(0.3*max(H(:))));
x = T(P(:,2));
y = R(P(:,1));
plot(x,y,'s','color','red');

%找到並繪製直線
%lines = houghlines(BW,T,R,P,'FillGap',1,'MinLength',100);
lines = houghlines(BW,T,R,P,'FillGap',5,'MinLength',5);
subplot(2,3,5);
imshow(BW),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','blue');

    %繪製線段端點
    plot(xy(1,1),xy(1,2),'x','LineWidth',2,'Color','yellow');
    plot(xy(2,1),xy(2,2),'x','LineWidth',2,'Color','red');

    % 確定最長線段
    len = norm(lines(k).point1-lines(k).point2);
    if (len > max_len)
        max_len = len;
        xy_long = xy;
    end
end

%高亮顯示最長線段
plot(xy_long(:,1),xy_long(:,2),'LineWidth',2,'Color','cyan');

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章