Examples
Template Matching
The comparison of two images is done based on correlation
coefficient.
The quantitative measure of the degree of association of two
distinct variables is often coined as correlation coefficient, which
typically ranges between -1 and 1.
Pearson Correlation coefficient
Template Matching (Cont’d)
Steps to be performed for finding the correlation coefficient between
two vectors or matrices
Template Matching (Cont’d)
This denotes that the matrix A and B are highly correlated.
MATLAB Code
A= [1 4 7; 2 5 8; 3 6 9]
B = A*2;
%Find the average of the matrix A
meanA = mean2(A);
%Find the average of the matrix B
meanB = mean2(B);
%Subtract the average value from matrix A
Asub = A-meanA;
%Subtract the average value from matrix B
Bsub = B-meanB;
Example: 2
%Covariance of matrix A and matrix B
%Assign new values to B
covAB = mean2(Asub.*Bsub);
B = [9 6 3;8 5 2; 7 4 1];
%Find the standard deviation of the matrix A
Rho = corr2(A,B)
stdA = std(A(:),1);
%Find the standard deviation of the matrix B
stdB = std(B(:),1);
%Find the correlation Cofficient
Rho = covAB./(stdA*stdB)
In the first example, both A and B are highly
correlated. The correlation coefficient is 1, whereas
in example 2, the correlation coefficient is -1.
Template Matching in Spatial Domain
%Read an Image A(Template)
A1 = imread('benten.jpg');
%Read the Target Image
B1 = imread('watch.jpg');
A = A1(:,:,1);
B = B1(:,:,1);
corr_map = zeros([size(A,1),size(A,2)]);
for i = 1:size(A,1)-size(B,1)
for j = 1:size(A,2)-size(B,2)
%Construct the correlation map
corr_map(i,j) = corr2(A(i:i+size(B,1)-1,j:j+size(B,2)-1),B);
end
end
Template Matching in Spatial Domain (Cont’d)
figure,imagesc(corr_map);colorbar;
%Find the maximum value
maxpt = max(corr_map(:));
[x,y]=find(corr_map==maxpt);
%Display the image from the template
figure,imagesc(B1);title('Target Image');colormap(gray);axis image
grayA = rgb2gray(A1);
Res = A;
Res(:,:,1)=grayA;
Res(:,:,2)=grayA;
Res(:,:,3)=grayA;
Res(x:x+size(B,1)-1,y:y+size(B,2)-1,:)=A1(x:x+size(B,1)1,y:y+size(B,2)-1,:);
figure,imagesc(Res);