Computing cross-correlation function? Computing cross-correlation function? numpy numpy

Computing cross-correlation function?


To cross-correlate 1d arrays use numpy.correlate.

For 2d arrays, use scipy.signal.correlate2d.

There is also scipy.stsci.convolve.correlate2d.

There is also matplotlib.pyplot.xcorr which is based on numpy.correlate.

See this post on the SciPy mailing list for some links to different implementations.

Edit: @user333700 added a link to the SciPy ticket for this issue in a comment.


If you are looking for a rapid, normalized cross correlation in either one or two dimensionsI would recommend the openCV library (see http://opencv.willowgarage.com/wiki/ http://opencv.org/). The cross-correlation code maintained by this group is the fastest you will find, and it will be normalized (results between -1 and 1).

While this is a C++ library the code is maintained with CMake and has python bindings so that access to the cross correlation functions is convenient. OpenCV also plays nicely with numpy. If I wanted to compute a 2-D cross-correlation starting from numpy arrays I could do it as follows.

import numpyimport cv#Create a random template and place it in a larger imagetemplateNp = numpy.random.random( (100,100) )image = numpy.random.random( (400,400) )image[:100, :100] = templateNp#create a numpy array for storing resultresultNp = numpy.zeros( (301, 301) )#convert from numpy format to openCV formattemplateCv = cv.fromarray(numpy.float32(template))imageCv = cv.fromarray(numpy.float32(image))resultCv =  cv.fromarray(numpy.float32(resultNp))#perform cross correlationcv.MatchTemplate(templateCv, imageCv, resultCv, cv.CV_TM_CCORR_NORMED)#convert result back to numpy arrayresultNp = np.asarray(resultCv)

For just a 1-D cross-correlation create a 2-D array with shape equal to (N, 1 ). Though there is some extra code involved to convert to an openCV format the speed-up over scipy is quite impressive.


I just finished writing my own optimised implementation of normalized cross-correlation for N-dimensional arrays. You can get it from here.

It will calculate cross-correlation either directly, using scipy.ndimage.correlate, or in the frequency domain, using scipy.fftpack.fftn/ifftn depending on whichever will be quickest.