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?