% Demo to show that cross correlation with xcorr2() does not find a template in an image, in general, but normxcorr2() does.
clc;    % Clear the command window.
close all;  % Close all figures (except those of imtool.)
clear;  % Erase all existing variables. Or clearvars if you want.
workspace;  % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;

%--------------------------------------------------------------------------------------------------------
%    READ IN IMAGE
folder = pwd;
baseFileName = 'coins.png';
grayImage = imread(baseFileName);
% Get the dimensions of the image.
% numberOfColorChannels should be = 1 for a gray scale image, and 3 for an RGB color image.
[rows, columns, numberOfColorChannels] = size(grayImage)
if numberOfColorChannels > 1
	% It's not really gray scale like we expected - it's color.
	% Use weighted sum of ALL channels to create a gray scale image.
	grayImage = min(grayImage, [], 3);
end

%--------------------------------------------------------------------------------------------------------
% Display the image.
subplot(2, 2, 1);
imshow(grayImage, []);
axis('on', 'image');
title('Binary Image', 'FontSize', fontSize, 'Interpreter', 'None');
impixelinfo;
hFig = gcf;
hFig.WindowState = 'maximized'; % May not work in earlier versions of MATLAB.
drawnow;

% Define template we want to look for
template = grayImage(59:111, 83:137);
%--------------------------------------------------------------------------------------------------------
% Display the image.
subplot(2, 2, 2);
imshow(template, []);
[rows2, columns2] = size(template)
axis('on', 'image');
title('Template Image', 'FontSize', fontSize, 'Interpreter', 'None');
impixelinfo;
drawnow;

% Do the correlation
% corrImage = xcorr2(grayImage, template);
corrImage = normxcorr2(template, grayImage);
[rows3, columns3] = size(corrImage)
% Crop the image
corrImage = imcrop(corrImage, [(columns3-columns)/2, (rows3-rows)/2, columns, rows]);

% Display the image.
subplot(2, 2, 3);
imshow(corrImage, []);
axis('on', 'image');
title('Correlation Image.  Max at red crosshairs', 'FontSize', fontSize, 'Interpreter', 'None');
impixelinfo;
drawnow;

% Find the max
maxValue = max(corrImage(:))
[y, x] = find(corrImage == maxValue)
% Plot the max over the correlation image
hold on;
plot(x, y, 'r+', 'LineWidth', 2, 'MarkerSize', 50);

% Plot it over the original image
subplot(2, 2, 4);
imshow(grayImage, []);
axis('on', 'image');
title('Binary Image', 'FontSize', fontSize, 'Interpreter', 'None');
impixelinfo;
% Plot where the correlation max is.
hold on;
plot(x, y, 'r+', 'LineWidth', 4, 'MarkerSize', 50);
% Plot where the template ACTUALLY came from.
plot(mean([83,137]), mean([59,111]), 'g+', 'LineWidth', 4, 'MarkerSize', 50);
title('Green = Template location, Red = correlation max', 'FontSize', fontSize, 'Interpreter', 'None');
