當前位置:編程學習大全網 - 源碼下載 - 如何用Hough變換檢測壹幅二值圖像中的最長直線

如何用Hough變換檢測壹幅二值圖像中的最長直線

樓主可以試壹下這段代碼,希望能對妳有幫助

I = imread('E:\pic\2\編號\4.bmp');%讀取圖像

rotI = imrotate(I,-4,'crop');%圖像旋轉33°

subplot(221),

fig1 = imshow(I);%在第壹幅子圖中繪制旋轉後的圖像

BW = edge(I,'canny');%使用canny方法檢測目標邊界

subplot(222),

imshow(BW);%顯示邊界的二值圖像

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

subplot(223),

imshow(imadjust(mat2gray(H)),[],'XData',theta,'YData',rho,...

'InitialMagnification','fit');%顯示hough變換的變換矩陣

xlabel('\theta (degrees)'), ylabel('\rho');

axis on, axis normal, hold on;

colormap(hot)%顏色映射表

P = houghpeaks(H,5,'threshold',ceil(0.3*max(H(:))));%hough變換的極值點

x = theta(P(:,2));

y = rho(P(:,1));

plot(x,y,'s','color','black');%畫出極值點

lines = houghlines(BW,theta,rho,P,'FillGap',...

5,'MinLength',7);%返回直線的端點%

subplot(224),

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(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');%繪制最長的直線

  • 上一篇:探究大自然,壹起與紅旗H5偶遇鳥巢,很美好
  • 下一篇:孫悟空在天庭大鬧的時候,他的搭檔為什麽不幫忙?
  • copyright 2024編程學習大全網