# Sub-pixel precision template matching using normalized cross-correlation (normxcorr2)

10 views (last 30 days)
Igor on 3 Feb 2022
Edited: Igor on 3 Feb 2022
Hello!
I am using normxcorr2 function to compute the displacement and velocity of certain region between two images. The problem is that normxcorr2 function returns result as an integer value and it doesn't evaluate sub-pixel displacemeent.
The only solution that I found is using imresize function with bicubic interpolation. I increase the size of the image 5 times and obtain better accuracy.
My question is: Is using of imresize the only option to get sub-pixel precision template matching using nomxcorr2 or are there any better options?
Original image pair:
t
t + dt, dt > 0
Here is the image pair processing result without scaling and the corresponding cross-correlation surface:
This is the image pair processing result with scaling using imresize function (x5 scaling), the measured velocity is now closer to the real one:
firstImage = imresize(firstImage, 5, 'bicubic');
secondImage = imresize(secondImage, 5, 'bicubic');
The main part of my code calculating normalized cross-correlation:
function [offsetX, offsetY] = calculateCrossCorrelation(refImage, targetImage, displayImages)
if displayImages
figure(1);
imshowpair(refImage, targetImage, 'montage');
end
c = normxcorr2(refImage, targetImage);
if displayImages
figure();
surf(c);
shading flat;
end
% Find the peak in cross-correlation
[ypeak,xpeak] = find(c==max(c(:)));
% Account for the padding that normxcorr2 adds
yoffSet = ypeak-size(refImage,1);
xoffSet = xpeak-size(refImage,2);
if displayImages
figure(3);
imshow(targetImage);
drawrectangle(gca,'Position',[xoffSet, yoffSet,...
size(refImage,2), size(refImage,1)], ...
'FaceAlpha',0);
end
offsetX = xoffSet;
offsetY = yoffSet;
end
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Categories

Find more on Template Matching in Help Center and File Exchange

R2020b

### Community Treasure Hunt

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

Start Hunting!

Translated by