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 recoveredfprintf('\n Input offset: %d,%d\n Recovered offset: %d,%d\n',offset,corr_offset)
Best Answer