Normalized Cross-Correlation in Python

Nice Question. There is no direct way but you can "normalize" the input vectors before using np.correlate like this and reasonable values will be returned within a range of [-1,1]:

Here i define the correlation as generally defined in signal processing textbooks.

c'_{ab}[k] = sum_n a[n] conj(b[n+k])

CODE: If a and b are the vectors:

a = (a - np.mean(a)) / (np.std(a) * len(a))
b = (b - np.mean(b)) / (np.std(b))
c = np.correlate(a, b, 'full')

References:

https://docs.scipy.org/doc/numpy/reference/generated/numpy.correlate.html

https://en.wikipedia.org/wiki/Cross-correlation

enter image description here


MATLAB ➜ xcorr(a, b, 'normalized');

MATLAB normalized cross-correlation implementation in Python.

import numpy as np
a = [1, 2, 3, 4]
b = [2, 4, 6, 8]
norm_a = np.linalg.norm(a)
a = a / norm_a
norm_b = np.linalg.norm(b)
b = b / norm_b
c = np.correlate(a, b, mode = 'full')