我是Matlab的新手,我想在不使用Matlab内置函数的情况下实现霍夫变换;因此,我正在学习这样做的可能方法。我发现在一本书中写的一个函数似乎是正确的。我遇到错误,无法解决。
我想实现霍夫变换功能,然后将其应用于灰度图像
% This functions makes use of sparse matrices
function [h, theta, rho] = HT(f, dtheta, drho)
% [H, THETA, RHO] = HOUGH(F, DTHETA, DRHO) computes the hough
% transform of the image F. DTHETA specifies the spacing (in degrees) of
% the the hough transform bins along the theta axis.
% DRHO specifies the spacing of the hough transform bins along the rho
% axis. H is the Hough transform matrix. It is NRHO-by-NTHETA, where
% NRHO = 2*ceil(norm(size(F))/DRHO) - 1, and NTHETA = 2*ceil(90/DTHETA).
if nargin < 3
drho = 1;
end
if nargin < 2
dtheta = 1;
end
f = double(f);
[M,N] = size(f);
theta = linspace(-90, 0, ceil(90/dtheta) + 1);
theta = [theta -fliplr(theta(2:end - 1))];
ntheta = length(theta);
D = sqrt((M - 1)^2 + (N - 1)^2);
q = ceil(D/drho);
nrho = 2*q - 1;
rho = linspace(-q*drho, q*drho, nrho);
[x, y, val] = find(f);
x = x - 1; y = y-1;
%Initialize output.
h = zeros(nrho, length(theta));
% To avoid excessive memory usage, process 1000 nonzero pixel
% values at a time.
for k = 1:ceil(length(val)/1000)
first = (k-1)*1000 + 1;
last = min(first+999, length(x));
x_matrix = repmat(x(first:last), 1, ntheta);
y_matrix = repmat(y(first:last), 1, ntheta);
val_matrix = repmat(val(first:last), 1, ntheta);
theta_matrix = repmat(theta, size(x_matrix, 1), 1)*pi/180;
rho_matrix = x_matrix.*cos(theta_matrix) + ...
y_matrix.*sin(theta_matrix);
slope = (nrho - 1)/(rho(end) - rho(1));
rho_bin_index = round(slope*(rho_matrix - rho(1)) + 1);
theta_bin_index = repmat(1:ntheta, size(x_matrix, 1), 1);
h = h + full(sparse(rho_bin_index(:), theta_bin_index(:), ...
val_matrix(:), nrho, ntheta));
end
%Illustration of Hough transform on a simple binary image
f = zeros(101, 101);
f(1, 1) = 1; f(101, 1) = 1; f(1, 101) = 1;
f(101, 101) = 1; f(51, 51) = 1;
% Compute & display the hough
H = HT(f);
imshow(H, [])
%Label the axis
[H, theta, rho] = HT(f);
imshow(theta, rho, H, [ ], 'notruesize')
axis on, axis normal
xlabel('\theta', ylabel('\rho'))
我希望使用imshow显示hough变换,但出现此错误
HT(f,dtheta,drho) 无法识别的函数或变量'f'。
答案 0 :(得分:1)
这里提供的是脚本和功能在单个.m文件中的组合。从Matlab R2016b开始允许这样做,但是规则是在脚本完成后具有函数定义。
因此您的代码应如下所示:
%Illustration of Hough transform on a simple binary image
f = zeros(101, 101);
f(1, 1) = 1; f(101, 1) = 1; f(1, 101) = 1;
f(101, 101) = 1; f(51, 51) = 1;
% Compute & display the hough
H = HT(f);
imshow(H, [])
%Label the axis
[H, theta, rho] = HT(f);
imshow(theta, rho, H, [ ], 'notruesize')
axis on, axis normal
xlabel('\theta', ylabel('\rho'))
function [h, theta, rho] = HT(f, dtheta, drho)
if nargin < 3
drho = 1;
end
if nargin < 2
dtheta = 1;
end
%.... the rest of the function
end