%% 学习目标:图像hough变换直线检测
RGB = imread('gantrycrane.png');
I = rgb2gray(RGB); % 转化成灰度图像
BW = edge(I,'canny'); % 提取边界
[H,T,R] = hough(BW,'RhoResolution',0.5,'ThetaResolution',0.5);
% 显示原始图
subplot(2,1,1), imshow(RGB), title('原始图像');
%% 显示Hough矩阵
subplot(2,1,2);
imshow(imadjust(mat2gray(H)),'XData',T,'YData',R,...
'InitialMagnification','fit');
title('Hough变换后结果图');
xlabel('\theta'), ylabel('\rho');
axis on, axis normal, hold on;
colormap(hot);
%%
P = houghpeaks(H,5,'threshold',ceil(0.3*max(H(:))));
lines = houghlines(BW,T,R,P,'FillGap',5,'MinLength',7);
figure, 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','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
%% 保存图像
imwrite(I,'1.bmp','bmp');
imwrite(BW,'2.bmp','bmp');
H=H/(max(max(H)));
imwrite(H,'3.bmp','bmp');
%% 大仙QQ:1960009019
%% 在线教育微信公众号:大仙一品堂