Fast cross correlation method in Python

回眸只為那壹抹淺笑 提交于 2019-12-03 03:07:34

You're unlikely to get much faster than using an fft based correlation method.

import numpy
from scipy import signal

data_length = 8192

a = 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 comparison
d = 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 loop

In [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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!