% fig_xcorr_pattern.m
% illustrate cross correlation for object detection

nx = 128; ny = 128;
f = zeros(nx,ny);
ix = [22 64 99 32 74 112];
iy = [30 40 40 84 114 84];
f(sub2ind([nx ny], ix, iy)) = 1;
pattern = ones(15,15);
pattern(9:15,1:7) = 0;
f = conv2(f, pattern, 'same');
rng(0)
sig = 2;
g = f + sig * randn(size(f));

scale = norm(pattern(:))^2;
pattern = pattern / scale; % normalize so that 0.5 threshold works ok
%r = xcorr2(g, pattern); % does not provide a 'same' option, annoyingly
r = conv2(g, fliplr(flipud(pattern)), 'same'); % trick: xcorr2 with 'same'

im plc 2 3
im(1, f);
titlef '$f$'
colormap(gca, 1-gray(256))
%set(gca, 'position', get(gca, 'position') + [0 0.25 0.0 0])
cbar h

tmp = ir_pad_into_center(pattern, nx);
% tmp = padarray(pattern, round((nx - size(pattern))/2), 'both'); % ugh
im(4, tmp)
titlef 'pattern'
cbar h notick
colormap(gca, 1-gray(256))

rlim = [-0.2 1.2];
im(2, g, rlim), cbar h
titlef '$g = f + $ noise'
colormap(gca, 1-gray(256))
ylabelf('SNR = %.1f dB', 20*log10(norm(f(:)) / norm(g(:)-f(:))))

im(3, r, rlim), cbar h
titlef '$r $ = xcorr2($g$, pattern)'
colormap(gca, 1-gray(256))

im(5, g > 0.5), cbar h
titlef '$g > 0.5$'
colormap(gca, 1-gray(256))

im(6, r > 0.5), cbar h
titlef '$r > 0.5$'
colormap(gca, 1-gray(256))

% ir_savefig fig_xcorr_pattern
