频域和空域的互相关 - 模板匹配

时间:2014-10-09 07:13:00

标签: matlab image-processing 2d template-matching frequency-domain

因此,当我尝试在大图像A中找到模板B时,我可以通过找到最大的互相关来实现,就像在空间域中一样:

%       Finding maximum of correlation:
        phi = normxcorr2(B,A); 
        [ymax, xmax] = find(phi == max(phi(:)));

%       Find position in original image:
        ypeak = ymax - size(B,1);
        xpeak = xmax - size(B,2);

但是当我想在频域中进行操作时,我得到了错误的结果:

%       Calculate correlation in frequency domain:
        Af = fft2(A);
        Bf = fft2(B, size(A,1), size(A,2));
        phi2f = conj(Af)'*Bf;

%       Inverse fft to get back to spatial domain:       
        phi2 = real(ifft(fftshift(phi2f)));

%       Now we have correlation matrix, excatly the same as calculated in
%       the spatial domain.
        [ymax2, xmax2] = find(phi2 == max(phi2(:)));

我不明白我在频域中做错了什么。我试过它没有fftshift,它给出了不同的结果,尽管还是一个错误的结果。我怎么能正确地做到这一点?

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题:

t   = imread('cameraman.tif');
a   = imtranslate(t, [15, 25]);

% Determine padding size in x and y dimension
size_t      = size(t);
size_a      = size(a);
outsize     = size_t + size_a - 1;

% Determine 2D cross correlation in Fourier domain
Ft = fft2(t, outsize(1), outsize(2));
Fa = fft2(a, outsize(1), outsize(2));
c = abs( fftshift( ifft2(Fa .* conj(Ft))) );

% Find peak
[max_c, imax]   = max(abs(c(:)));
[ypeak, xpeak]  = ind2sub(size(c), imax(1));

% Correct found peak location for image size
corr_offset = round([(ypeak-(size(c, 1)+1)/2) (xpeak-(size(c, 2)+1)/2)]);

% Write out offsets
y_offset = corr_offset(1)
x_offset = corr_offset(2)