霍夫变换是一种特征检测(feature extraction),被广泛应用在图像分析(image analysis)、电脑视觉 (computer vision)以及数位影像处理 (digital image processing)。 霍夫变换是用来辨别找出物件中的特征,例如:线条。他的算法流程大致如下,给定一个物件、要辨别的形状的种类,算法会在参数空间(parameter space)中执行投票来决定物体的形状, 而这是由累加空间(accumulator space)里的局部最大值(local maximum)来决定。
Hough变换的基本原理在于,利用点与线的对偶性,将图像空间的线条变为参数空间的聚集点,从而检测给定图像是否存在给定性质的曲线。
clc;clear ; close
set(0,'defaultfigurecolor',[1,1,1])
load DATA2.mat
data = D1;
BW = data;
figure(1)
imshow(BW)
title('原图像');
figure(2)
subplot 211;
%%进行霍夫变换
[H, theta , rho] = hough (BW);
%%绘制霍夫空间
imshow(imadjust(mat2gray(H)),[],'XData',theta,'YData',rho,...
'InitialMagnification','fit');
xlabel('\theta (degrees)'), ylabel('\rho');
axis on, axis normal, hold on;
colormap(hot);
title('霍夫空间')
%%峰值
P = houghpeaks(H,5,'threshold',0.5*max(H(:)));
x = theta(P(:,2));
y = rho(P(:,1));
plot(x,y,'s','color','black');
%lines = houghlines(BW,theta,rho,P,'FillGap',10,'MinLength',10);
lines = houghlines(BW,theta,rho,P,'FillGap',10,'MinLength',10);
subplot 212
imshow(BW) ,hold on
max_len = 0;
count = 1;
points = zeros(2,2);
for k = 1:length(lines)
points(count,1) = lines(k).point1(1);
points(count,2) = lines(k).point1(2);
count =count +1;
points(count,1) = lines(k).point2(1);
points(count,2) = lines(k).point2(2);
count =count +1;
xy = [lines(k).point1; lines(k).point2];
plot(xy(:,1),xy(:,2),'LineWidth',2,'Color','green');
% Plot beginnings and ends of lines
plot(xy(1,1),xy(1,2),'x','LineWidth',2,'Color','yellow');
plot(xy(2,1),xy(2,2),'x','LineWidth',2,'Color','red');
end
title('直线检测');
效果如下: