title: Matlab Template Matching Using FFT
body: <p>I am struggling with template matching in the Fourier domain in Matlab. Here are my images (the artist is RamalamaCreatures on DeviantArt): </p>
  
  <p><a href="https://i.stack.imgur.com/FXEy7.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/FXEy7.jpg" alt="possum.jpg"></a>
  <a href="https://i.stack.imgur.com/6bTzT.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/6bTzT.jpg" alt="possum_ear.jpg"></a></p>
  
  <p>My aim is to place a bounding box around the ear of the possum, like this example (where I performed template matching using normxcorr2): </p>
  
  <p><a href="https://i.stack.imgur.com/sl855.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/sl855.jpg" alt="Goal: possum ear bounded"></a> </p>
  
  <p>Here is the Matlab code I am using:</p>
  
  <pre><code>clear all; close all;
  
  template = rgb2gray(imread('possum_ear.jpg'));
  background = rgb2gray(imread('possum.jpg'));
  
  %% calculate padding
  bx = size(background, 2); 
  by = size(background, 1);
  tx = size(template, 2); % used for bbox placement
  ty = size(template, 1);
  
  %% fft
  c = real(ifft2(fft2(background) .* fft2(template, by, bx)));
  
  %% find peak correlation
  [max_c, imax]   = max(abs(c(:)));
  [ypeak, xpeak] = find(c == max(c(:)));
  figure; surf(c), shading flat; % plot correlation 
  
  %% display best match
  hFig = figure;
  hAx  = axes;
  position = [xpeak(1)-tx, ypeak(1)-ty, tx, ty];
  imshow(background, 'Parent', hAx);
  imrect(hAx, position);
  </code></pre>
  
  <p>The code is not functioning as intended - it is not identifying the correct region. This is the failed result - the wrong area is boxed:
   <a href="https://i.stack.imgur.com/DH9kg.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/DH9kg.jpg" alt="failed template matching"></a></p>
  
  <p>This is the surface plot of the correlations for the failed match: 
  <a href="https://i.stack.imgur.com/HwQJI.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/HwQJI.jpg" alt="surf plot for failed template matching"></a></p>
  
  <p>Hope you can help! Thanks. </p>