Matlab2016b图像处理-霍夫变换(新版)

来源:互联网 发布:js字符串获取指定下标 编辑:程序博客网 时间:2024/06/05 08:45

查到很多教程都是基于较老的版本,随着Matlab的更新,霍夫变换函数也发生了变换,基于新版本,重新对霍夫变换函数做出解释。

Matlab版本:

Matlab2016b

基本原理:

霍夫变换主要用来线检测,原理并不麻烦。
image.png
简单来说,无非就是,xy空间,一条直线上的一个点,对应到参数空间,变成一条曲线,一条直线上的多个点,也就对应了一簇曲线,一簇曲线的交点,即为这条直线。
主要讲解霍夫变换函数的使用。

相关函数

1.hough:实现霍夫变换

  • 基本语法[H,theta,rho] = hough(BW,Name,Value,...)
    输入参数:
    BW:一幅二值图像;
    Name:‘RhoResolution’和‘Theta’两种选择,而且相互对应,同时存在;
    RhoResolution:霍夫变换沿rho轴的间距,默认是1;
    Theta:所处理的直线的角度范围,默认是(-90,89);
    输出参数
    H:霍夫变换矩阵;
    theta:x轴和rho向量之间的角度;
    rho:原点到直线的距离。

  • 代码示例:该代码对检测直线的角度做出了限制。

% Read image and convert it to grayscale.RGB = imread('gantrycrane.png');I  = rgb2gray(RGB); % Extract edges.BW = edge(I,'canny'); % Calculate the Hough transform.[H,T,R] = hough(BW, 'Theta', 44:0.5:46);% Dislay the Hough transform.figureimshow(imadjust(mat2gray(H)),'XData',T,'YData',R,...   'InitialMagnification','fit');title('Limited Theta Range Hough Transform of Gantrycrane Image');xlabel('\theta'), ylabel('\rho');axis on, axis normal;colormap(gca,hot)
  • 效果图:
    image.png

2.houghpeaks:霍夫变换峰值检测

  • 基本语法:
    peaks = houghpeaks(H,numpeaks)
    peaks = houghpeaks(___,Name,Value,...)
    输入参数:
    H:霍夫变换矩阵;
    numpeaks:所检测峰值数目的最大值,默认为1;
    Name,Value:成对的参数,用于对峰值检测做出约束;
    Threshold:阈值,所检测峰值的最小值。默认是0.5*max(H(:));
    输出参数:
    peaks:所检测到的峰值的坐标矩阵;
  • 代码示例:与houghlines一起。

3.houghlines:霍夫变换线检测

  • 基本语法:
    lines = houghlines(BW,theta,rho,peaks)
    lines = houghlines(___,Name,Value,...)
    输入参数:
    BW:二值图像;
    theta:霍夫变换hough输出的角度;
    rho:霍夫变换hough输出的rho;
    peaks:霍夫变换峰值检测输出的峰值;
    输出参数
    lines:是一个结构数组,包括point1,point2,theta,rho,长度为所检测到的线的条数;
    point1,2:所检测到线的起止坐标;
    theta,rho:与前两个函数类似。
  • 代码示例
I  = imread('circuit.tif');% Rotate the image.rotI = imrotate(I,33,'crop');% Create a binary image.BW = edge(rotI,'canny');imshow(BW);% Create the Hough transform using the binary image.[H,T,R] = hough(BW);figure,imshow(H,[],'XData',T,'YData',R,...            'InitialMagnification','fit');xlabel('\theta'), ylabel('\rho');axis on, axis normal, hold on;% Find peaks in the Hough transform of the image.P  = houghpeaks(H,5,'threshold',ceil(0.3*max(H(:))));x = T(P(:,2)); y = R(P(:,1));plot(x,y,'s','color','white');% Find lines and plot them.lines = houghlines(BW,T,R,P,'FillGap',5,'MinLength',7);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 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');   % Determine the endpoints of the longest line segment   len = norm(lines(k).point1 - lines(k).point2);   if ( len > max_len)      max_len = len;      xy_long = xy;   endend% Highlight the longest line segment by coloring it cyan.plot(xy_long(:,1),xy_long(:,2),'LineWidth',2,'Color','cyan');
  • 效果图
    image.png
原创粉丝点击