0

因此,當我嘗試在大圖像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,它給出了不同的結果,儘管仍然是錯誤的。我怎樣才能正確地做到這一點?

+0

綜觀定義'normcorr2',我想我們可以假設B是模板,A是你的形象?我認爲如果你補充說明,那只是爲了清楚。 – kkuilla 2014-10-09 08:12:43

+1

@kkuilla編輯 – Vidak 2014-10-09 08:15:42

+0

如果您有圖像,請將它們與預期的和實際的輸出一起添加,以便它成爲一個可重複的示例。 – kkuilla 2014-10-09 08:19:44

回答

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) 
+0

有趣!你將如何改變你的代碼來計算標準化交叉相關版本? – 2016-11-30 15:53:49