Vidak
Vidak

Reputation: 1103

Cross-Correlation in Frequency and Spatial domain - Template Matching

So when I try to find a template B in a big image A, I can do it by finding the maximum of cross-correlation, like this in spatial domain:

%       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);

But when I want to do it in frequency domain, I get wrong results:

%       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(:)));

I don't understand what I'm doing wrong in the frequency domain. I've tried it without fftshift, it gives a different result, albeit a wrong one still. How can I do this correctly?

Upvotes: 0

Views: 2905

Answers (1)

Maurits
Maurits

Reputation: 2114

This should do the trick:

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)

Upvotes: 1

Related Questions