Cross-correlation in frequency domain and xcorr2 in MATLAB

조회 수: 8 (최근 30일)
Shy
Shy 2024년 5월 11일
댓글: Shy 2024년 5월 12일
What are the reasons for the differences between my frequency domain cross-correlation results and those obtained using the xcorr2() function in MATLAB? Is it possible that xcorr2() performs spatial domain cross-correlation, and how might this affect the results?
img1 = imread('1.jpg');
img2 = imread('2.jpg');
img1_gray = rgb2gray(img1);
img2_gray = rgb2gray(img2);
[m, n] = size(img1_gray);
[p, q] = size(img2_gray);
fft_img1 = fft2(img1_gray, m + p - 1, n + q - 1);
fft_img2 = fft2(img2_gray, m + p - 1, n + q - 1);
cross_correlation = (fft_img1 .* conj(fft_img2));
cross_correlation = ifft2(cross_correlation);
cross_correlation = fftshift(cross_correlation);
cross_correlation_xcorr2 = xcorr2(img2_gray, img1_gray);
figure;
subplot(2, 1, 1);
imshow(cross_correlation, []);
title('Custom Cross-Correlation');
subplot(2, 1, 2);
imshow(cross_correlation_xcorr2, []);
title('xcorr2');
Results:
  댓글 수: 2
Paul
Paul 2024년 5월 11일
Can you add 1.jpg and 2.jpg to your post using the Paperclip icon on the Insert menu?

댓글을 달려면 로그인하십시오.

채택된 답변

Paul
Paul 2024년 5월 11일
Hi Shy,
Assuming that the output of the xcorr2 is the expected result, it can be obtained with the changes below
img1 = imread('1.jpg');
img2 = imread('2.jpg');
img1_gray = rgb2gray(img1);
img2_gray = rgb2gray(img2);
[m, n] = size(img1_gray);
[p, q] = size(img2_gray);
%fft_img1 = fft2(img1_gray, m + p - 1, n + q - 1);
fft_img1 = fft2(flipud(fliplr(img1_gray)), m + p - 1, n + q - 1);
fft_img2 = fft2(img2_gray, m + p - 1, n + q - 1);
%cross_correlation = (fft_img1 .* conj(fft_img2));
cross_correlation = (fft_img1 .* fft_img2);
cross_correlation = ifft2(cross_correlation);
%cross_correlation = fftshift(cross_correlation);
cross_correlation_xcorr2 = xcorr2(img2_gray, img1_gray);
figure;
subplot(2, 1, 1);
imshow(cross_correlation, []);
title('Custom Cross-Correlation');
subplot(2, 1, 2);
imshow(cross_correlation_xcorr2, []);
title('xcorr2');
  댓글 수: 3
Paul
Paul 2024년 5월 11일
As I undersand it, xcorr2(x,y) is the the same as conv2 of x and the 2D-reversed conjugate of y. But in this case, img1_gray is real, so its conjugate is itself. With that understanding, I just made the fft stuff implement the convolution of img2 and the 2D-reverse of img1 (because img1 is the second argument to xcorr2).
Shy
Shy 2024년 5월 12일
Okay, I get it. Thanks

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Correlation and Convolution에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by