# 霍夫变换算法原理及matlab实现转载

## 霍夫变换

A-基本原理

到这里问题似乎解决了，已经完成了霍夫变换的求解，但是如果像下图这种情况呢？

k=∞是不方便表示的，而且q怎么取值呢，这样不是办法。因此考虑将笛卡尔坐标系换为：极坐标表示

 12345678910111213141516171819202122232425 function [ Hough, theta_range, rho_range ] = naiveHough(I)%NAIVEHOUGH Peforms the Hough transform in a straightforward way.%[rows, cols] = size(I); theta_maximum = 90;rho_maximum = floor(sqrt(rows^2 + cols^2)) - 1;theta_range = -theta_maximum:theta_maximum - 1;rho_range = -rho_maximum:rho_maximum; Hough = zeros(length(rho_range), length(theta_range));for row = 1:rows    for col = 1:cols        if I(row, col) > 0 %only find: pixel > 0            x = col - 1;            y = row - 1;            for theta = theta_range                rho = round((x * cosd(theta)) + (y * sind(theta)));  %approximate                rho_index = rho + rho_maximum + 1;                theta_index = theta + theta_maximum + 1;                Hough(rho_index, theta_index) = Hough(rho_index, theta_index) + 1;            end        end    endend

其实本质上就是：

B-理论应用

这里给出MATLAB自带的一个应用，主要是对一幅图像进行直线检验，原图像为：

给出对应的代码：

 1234567891011121314151617181920212223242526272829303132333435363738394041424344 clc;clear all;close all;I  = imread('circuit.tif');rotI = imrotate(I,40,'crop');subplot 221fig1 = imshow(rotI);BW = edge(rotI,'canny');title('原图像');subplot 222imshow(BW);[H,theta,rho] = hough(BW);title('图像边缘检测');subplot 223imshow(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,5,'threshold',ceil(0.7*max(H(:))));x = theta(P(:,2));y = rho(P(:,1));plot(x,y,'s','color','black');lines = houghlines(BW,theta,rho,P,'FillGap',5,'MinLength',7);title('Hough空间');subplot 224, 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 segmentplot(xy_long(:,1),xy_long(:,2),'LineWidth',2,'Color','red');title('直线检测');

对比自带的Hough与编写的Hough:

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120