You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
2.3 KiB
Matlab

function [y]=template_matching_zncc(I,Tboxes,Iquery,templates)
%This function performs template matching using correlation coefficient (aka
%zero-mean normalised cross correlation).
%
%The input is: an image, I; the location, defined by Tboxes, of a patch of
%this image; and a second image, Iquery. This function uses the target location
%in the first image as a template for finding the corresponding location in the
%second image. The output is an array, y, the same size as the second image
%that denotes the strength of the match between the template and each location
%in the second image.
%
%If Tboxes contains multiple rows, then template matching is performed for each
%template defined by each row, and y will by a three-dimensional array
%containing the similarity for each template to the image.
%
%If the input variable templates is specified, I and Tboxes are ignored and the
%given templates are matched to Iquery
if nargin>3
%apply ZNCC to find similarity between each given template and Iquery
numTemplates=length(templates);
else
%calc similarity between templates extracted from image I and Iquery
[a1,b1,c]=size(I);
%convert images to HSV colour space
if c==3
I=rgb2hsv(I);
end
numTemplates=size(Tboxes,1);
for t=1:numTemplates
%define the template as the given region of the first image
[templates{t}]=imcrop_odd(I,Tboxes(t,:));
end
end
[a2,b2,c]=size(Iquery);
%convert images to HSV colour space
if c==3
Iquery=rgb2hsv(Iquery);
end
%calc similarity of given templates and Iquery
y=zeros(a2,b2,numTemplates,'single'); %pre-allocate memory
for t=1:numTemplates
%perform matching of the template to the second image: summing correlation over colour channel
ytmp=single(0);
for colour=1:c
%ytmp=ytmp+conv2(Iquery(:,:,colour),rot90(T{t}(:,:,colour)),'same'); %cross-correlation
ytmp=ytmp+single(normxcorr2(templates{t}(:,:,colour),Iquery(:,:,colour))); %correlation coeff
end
ytmp=ytmp(floor(size(templates{t},1)/2)+[1:a2],floor(size(templates{t},2)/2)+[1:b2]); %remove padding applied by normxcorr2
y(:,:,t)=ytmp; %combine results for transformed templates
end
%suppress matches within half the bounding box of the image boundary (this trick is used by BBS):
%y(1:floor(Tbox(4)/2),:,:)=0; y(a-floor(Tbox(4)/2)+1:a,:,:)=0; y(:,1:floor(Tbox(3)/2),:)=0; y(:,b-floor(Tbox(3)/2)+1:b,:)=0;