霍夫变换在图像处理里常用来在黑白图像里检测直线,matlab里有相应的几个函数,使用方便,这里把matlab帮助里介绍的例子演示一下。 matlab里霍夫变换主要包含一下三个函数:hough:实现霍夫变换,得到霍夫变换矩阵,用法如下[H, theta, rho] = hough(BW)[H, theta, rho] = hough(BW, ParameterName,ParameterValue)houghpeaks:在霍夫变换矩阵里找极值点peaks = houghpeaks(H, numpeaks)peaks = houghpeaks(..., param1, val1,param2, val2)houghlines:从霍夫变换矩阵中提取线段lines = houghlines(BW, theta, rho,peaks)lines = houghlines(..., param1, val1,param2, val2) 下面以一个例子来看看霍夫变换的效果,代码如下: % 测试霍夫变换clcclearclose all % 读取图像I = imread('circuit.tif');rotI = imrotate(I,80,'crop'); % 旋转33度,保持原图片大小fig1 = imshow(rotI); % 提取边BW = edge(rotI,'canny');figure, imshow(BW); % 霍夫变换[H,theta,rho] = hough(BW); % 计算二值图像的标准霍夫变换,H为霍夫变换矩阵,theta,rho为计算霍夫变换的角度和半径值figure, imshow(imadjust(mat2gray(H)),[],'XData',theta,'YData',rho,... 'InitialMagnification','fit');xlabel('\theta (degrees)'), ylabel('\rho');axis on, axis normal, hold on;colormap(hot) % 显示霍夫变换矩阵中的极值点P = houghpeaks(H,50,'threshold',ceil(0.3*max(H(:)))); % 从霍夫变换矩阵H中提取5个极值点x = theta(P(:,2));y = rho(P(:,1));plot(x,y,'s','color','black'); % 找原图中的线lines = houghlines(BW,theta,rho,P,'FillGap',18,'MinLength',180);figure, imshow(rotI), hold onmax_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; endend % 以红色线高亮显示最长的线plot(xy_long(:,1),xy_long(:,2),'LineWidth',2,'Color','red'); 其中,同一条线段由于某些原因(比如光照、噪音等)变成了不连续的两条较短的线段,所以要进项合并,至于多少长度的才合并成同一条直线,是依据不同的图像而言的,由fillgap参数决定。而有些线段可能是噪声,所以小于7的舍去,这个也么有标准,需要根据不同的图像而定。