Fast cross correlation method in Python
You're unlikely to get much faster than using an fft based correlation method.
import numpyfrom scipy import signaldata_length = 8192a = numpy.random.randn(data_length)b = numpy.zeros(data_length * 2)b[data_length/2:data_length/2+data_length] = a # This works for data_length being even# Do an array flipped convolution, which is a correlation.c = signal.fftconvolve(b, a[::-1], mode='valid') # Use numpy.correlate for comparisond = numpy.correlate(a, a, mode='same')# c will be exactly the same as d, except for the last sample (which # completes the symmetry)numpy.allclose(c[:-1], d) # Should be True
Now for a time comparison:
In [12]: timeit b[data_length/2:data_length/2+data_length] = a; c = signal.fftconvolve(b, a[::-1], mode='valid')100 loops, best of 3: 4.67 ms per loopIn [13]: timeit d = numpy.correlate(a, a, mode='same')10 loops, best of 3: 69.9 ms per loop
If you can cope with a circular correlation, you can remove the copy. The time difference will increase as data_length
increases.
I believe your code fails because OpenCV is expecting images as uint8 and not float32 format.You may find the cv2 python interface more intuitive to use (automatic conversion between ndarray and CV Image formats).
As for the speed of correlation, you can try using a fast fft implementation (FFTW has a python wrapper : pyfftw).