xcorr2 VS“手动”互相关

时间:2018-04-23 10:07:39

标签: matlab fft offset cross-correlation

我编写了一个短代码,它使用xcorr2执行两个图像的“手动”互相关和交叉相关。目标是找到两个图像之间的偏移(以像素为单位)。

我不明白为什么,但这两种方法都给我带来了截然不同的结果。

xcorr2方法已经通过这种方式实现:

clc
close all
%Cropping the bitmaps into the 2 sections I Want to cross-correlate, placing them in the center of new bitmaps with 2^n dimensions
ExpInitCrop = imcrop(BMInit,[1, 157, 1024, 131]); %Size of cropped images : 132*1024
ExpFinalCrop = imcrop(BMFinal,[1, 157, 1024, 131]);
ExpInitLarge = padarray(ExpInitCrop, [190, 512]); %Total size of both images : 512*2048
ExpFinalLarge = padarray(ExpFinalCrop, [190, 512]);

%Grayscalling the 2 sections
ExpInitLargeGS = ind2gray(ExpInitLarge, mapInit);
ExpFinalLargeGS = ind2gray(ExpFinalLarge, mapFinal);

%xcorr
tic
XCorrExp = xcorr2(ExpInitLargeGS, ExpFinalLargeGS);
toc
whos XCorrExp
mesh(XCorrExp)

%Finding shift alongside X and Y axis
[max_XCorrExp, imax] = max(abs(XCorrExp(:)));
[ypeak, xpeak] = ind2sub(size(XCorrExp),imax(1));
corr_offset = [(ypeak-size(ExpInitLarge,1)) (xpeak-size(ExpInitLarge,2))]

xcorr2函数需要大约85-90秒才能计算出来。输出矩阵XCorrExp的大小为1023 * 4096。计算的偏移量为(-2,-37),这看起来完全符合输入数据。

现在,使用以下公式实现了“手动”互相关:corr(a, b) = ifft(fft(a_and_zeros) * conj(fft(b_and_zeros))),这是交叉关联两个信号的公式。 这是代码:

clc
close all
%Cropping the bitmaps into the 2 sections I Want to cross-correlate, placing them in the center of new bitmaps with 2^n dimensions
ExpInitCrop = imcrop(BMInit,[1, 157, 1024, 131]); %Size of cropped images : 132*1024
ExpFinalCrop = imcrop(BMFinal,[1, 157, 1024, 131]);
ExpInitLarge = padarray(ExpInitCrop, [190, 512]); %Total size of both images : 512*2048
ExpFinalLarge = padarray(ExpFinalCrop, [190, 512]);

tic
%Grayscalling the 2 sections
ExpInitLargeGS = ind2gray(ExpInitLarge, mapInit);
ExpFinalLargeGS = ind2gray(ExpFinalLarge, mapFinal);

%FFT
ExpInitFFT = fft2(ExpInitLargeGS);
ExpFinalFFT = fft2(ExpFinalLargeGS);

%Conjugating complex values
for i = 1:size(ExpFinalFFT,1)
    for j = 1:size(ExpFinalFFT,2)
        ExpFinalFFT(i,j) = conj(ExpFinalFFT(i,j));
    end
end

%Element-wise multiplication
ExpMultipliedMatrix = times(ExpInitFFT, ExpFinalFFT);

%IFFT
XCorrExp = ifft2(ExpMultipliedMatrix);
XCorrExpShift = fftshift(XCorrExp);
toc
whos XCorrExpShift
mesh(XCorrExpShift)

%Finding shift alongside X and Y axis
[max_XCorrExpShift, imax] = max(abs(XCorrExpShift(:)));
[ypeak, xpeak] = ind2sub(size(XCorrExpShift),imax(1));
corr_offset = [(ypeak-size(ExpInitLarge,1)) (xpeak-size(ExpInitLarge,2))]

“手动”方法需要大约0.7-0.8秒才能计算出来。输出矩阵XCorrExpShift的大小为512 * 2048。计算出的偏移量为(-257,-1060),根据输入数据显示为WAY,WAY off。

我很难理解为什么我的“手动”方法没有提供与xcorr2方法相同的结果。有人能够向我解释这个吗? xcorr2我的手动方法没有做什么?

谢谢!

编辑:预期输出与xcorr2方法给出的偏移量相同。但我还想了解为什么这样的计算时间差异很大。 Here is the first input bitmap Here is the second

0 个答案:

没有答案