How To Find Correlation Between Two Images Using Numpy

- 1 answer

This is inspired by this question.

I'm trying to find correlation between two grayscale images using Numpy. Using SciPy's correlate2d we can find this. I have found Numpy's corrcoef but results are different when I compared with correlate2d. Hence this question- Is there correlate2d equivalent in Numpy?



As far as I can tell, this produces the same result as scipy.correlate2d(), where img1 and img2 are 2d arrays representing greyscale (i.e. single-channel) images:

import numpy as np

pad = np.max(img1.shape) // 2
fft1 = np.fft.fft2(np.pad(img1, pad))
fft2 = np.fft.fft2(np.pad(img2, pad))
prod = fft1 * fft2.conj()
result_full = np.fft.fftshift(np.fft.ifft2(prod))
corr = result_full.real[1+pad:-pad+1, 1+pad:-pad+1]

The single-pixel cropping adjustment is not very elegant but that's FFTs for you: fiddly.

I just want to say that scipy is perfectly fine to use and I strongly recommend it. Having said that, this approach does seem to be a lot faster for the single case I tried.