Skip to content

Instantly share code, notes, and snippets.

@calum-chamberlain
Created February 28, 2017 03:30
Show Gist options
  • Save calum-chamberlain/12b5dd422c979b3410b809429979e999 to your computer and use it in GitHub Desktop.
Save calum-chamberlain/12b5dd422c979b3410b809429979e999 to your computer and use it in GitHub Desktop.
def normxcorr1(template, search_window):
"""
Normlized cross-correlation using scipy - contributed by d-chambers.
:type template: :class:`numpy.ndarray`
:param template: 1D numpy array to use as template
:type search_window: :class: `numpy.ndarray`
:param search_window: 1D numpy array to search for the template within.
:rtype: :class: `numpy.ndarray`
:returns: Normalized cross-correlation vector.
"""
# cast to float 32
template = template.astype(np.float32)
search_window = search_window.astype(np.float32)
# switch t and s if t is larger than s
if len(template) > len(search_window):
template, search_window = search_window, template
n = len(template)
nt = (template - np.mean(template)) / (np.std(template) * n)
a = bottleneck.move_mean(search_window, n)[n - 1:]
b = bottleneck.move_std(search_window, n)[n - 1:]
c = fftconvolve(nt[::-1], search_window, mode="valid")
result = (c - nt.sum() * a) / b
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment