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