www.gusucode.com > images 案例代码 matlab源码程序 > images/UseCrossCorrelationToFindTemplateInImageExample.m

    %% Use Cross-Correlation to Find Template in Image 
% 
%%
% Read images into the workspace and display them side-by-side.
onion   = rgb2gray(imread('onion.png'));
peppers = rgb2gray(imread('peppers.png'));
imshowpair(peppers,onion,'montage')
%%
% Perform cross-correlation and display result as surface.
c = normxcorr2(onion,peppers);
figure, surf(c), shading flat
%%
% Find peak in cross-correlation. 
[ypeak, xpeak] = find(c==max(c(:)));
%%
% Account for the padding that |normxcorr2| adds. 
yoffSet = ypeak-size(onion,1);
xoffSet = xpeak-size(onion,2);
%%
% Display matched area.
hFig = figure;
hAx  = axes;
imshow(peppers,'Parent', hAx);
imrect(hAx, [xoffSet+1, yoffSet+1, size(onion,2), size(onion,1)]);