Why are my results different in xcorr2 and normxcorr2 in MATLAB 7.7 (R2008b)?

15 views (last 30 days)
I expected the corr_offset variable output by the above code to have the same value when either normxcorr2 or xcorr2 is called. But the correlation matrix produced by these two functions places the peak value in a different place. I expected the peak to have a different value (the effect of the normalization in normxcorr2) but I didn't expect it to be in a different place. If you look at the images of cc_norm and cc, you'll see the effect.
template = .2*ones(11); % Make light gray plus on dark gray background
template(6,3:9) = .6;
template(3:9,6) = .6;
BW = single(template > 0.5); % Make white plus on black background
figure, imshow(BW), figure, imshow(template)
% Make new image that offsets the template
offsetTemplate = .2*ones(21);
offset = [3 5]; % Shift by 3 rows, 5 columns
offsetTemplate( (1:size(template,1))+offset(1),...
(1:size(template,2))+offset(2) ) = template;
figure, imshow(offsetTemplate)
% normxcorr2
% Cross-correlate BW and offsetTemplate to recover offset
fprintf('\nTest using normxcorr2:\n')
cc_norm = normxcorr2(BW,offsetTemplate);
figure, imagesc(cc_norm), axis xy
[max_cc_norm, imax] = max(abs(cc_norm(:)))
[ypeak, xpeak] = ind2sub(size(cc_norm),imax(1));
corr_offset = [ (ypeak-size(template,1)) (xpeak-size(template,2)) ];
%isequal(corr_offset,offset) % 1 means offset was recovered
fprintf('\n Input offset: %d,%d\n Recovered offset: %d,%d\n',offset,corr_offset)
% xcorr2
% Cross-correlate BW and offsetTemplate to recover offset
fprintf('\nTest using xcorr2:\n')
cc = xcorr2(BW,offsetTemplate);
figure, imagesc(cc), axis xy
[max_cc, imax] = max(abs(cc(:)))
[ypeak, xpeak] = ind2sub(size(cc),imax(1));
corr_offset = [ (ypeak-size(template,1)) (xpeak-size(template,2)) ];
%isequal(corr_offset,offset) % 1 means offset was recovered
fprintf('\n Input offset: %d,%d\n Recovered offset: %d,%d\n',offset,corr_offset)

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 5 Aug 2009
There is a subtle difference between normxcorr2 and xcorr2 in their function call syntaxes. For normxcorr2(A,B), the function slides A through B. Therefore, normxcorr2(Template,Image) means that it looks for the match of Template in Image. For xcorr2(A,B), the function actually slides B through A. Therefore, to achieve the similar functionality as in normxcorr2, it has to be invoked in the form of xcorr2(Image, Template). Unlike normxcorr2 though, xcorr2 does not require the size of B to be larger than size of A, so you may not notice it at all but the result becomes unexpected. To get the correct result, you would need to swap the inputs to xcorr2 in your script and you'll see the resulting offsets are correct.

More Answers (0)

Products


Release

R2008b

Community Treasure Hunt

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

Start Hunting!