Computing cross-correlation function?

前端 未结 4 1999
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 20:49

In R, I am using ccf or acf to compute the pair-wise cross-correlation function so that I can find out which shift gives me the maximu

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 21:18

    If you are looking for a rapid, normalized cross correlation in either one or two dimensions I 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 numpy
    import cv
    
    #Create a random template and place it in a larger image
    templateNp = numpy.random.random( (100,100) )
    image = numpy.random.random( (400,400) )
    image[:100, :100] = templateNp
    
    #create a numpy array for storing result
    resultNp = numpy.zeros( (301, 301) )
    
    #convert from numpy format to openCV format
    templateCv = cv.fromarray(numpy.float32(template))
    imageCv = cv.fromarray(numpy.float32(image))
    resultCv =  cv.fromarray(numpy.float32(resultNp))
    
    #perform cross correlation
    cv.MatchTemplate(templateCv, imageCv, resultCv, cv.CV_TM_CCORR_NORMED)
    
    #convert result back to numpy array
    resultNp = 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.

提交回复
热议问题