0

As per this post the cross-correlation between 2 images is obtained as it follows:

def cross_correlate_2d(x, h):
        h = ifftshift(ifftshift(h, axes=0), axes=1)
        return ifft2(fft2(x) * np.conj(fft2(h))).real

x = np.array(Image.open("covid.png").convert("L")) / 255. h1 = x.copy() out1 = cross_correlate_2d(x, h1)

This works fine in case the images have same dimensions, otherwise (when sizes differ) the multiplication

fft2(x) * np.conj(fft2(h))

will not work since the rule for matrices multiplication is not respected (nrCols 1st matrix = nrRows 2nd matrix)

Let's say the template image is smaller in dimensions.

Could i fill it with 0's up until the target image rows and cols values are obtained and after that fft2D it and then continue the process?

OverLordGoldDragon
  • 8,912
  • 5
  • 23
  • 74

1 Answers1

1

The answer's in the second example of your linked post:

This is the original template:

So yes, we zero-pad, but not just in any arbitrary way - the template must become centered - applying code at bottom:

If we instead right-padded (i.e. np.pad(x, [0, pad0], [0, pad1])), output is shifted:

If instead template is bigger than target, then it doesn't matter how we pad the target, as long as we unpad correctly (i.e. undo the padding) and both inputs end up at same shape. Note there's no unpadding if we're only padding the template.

import numpy as np
import matplotlib.pyplot as plt

x_target = np.random.randn(512, 512) x_template = np.random.randn(321, 34)

pad_vert1 = (x_target.shape[0] - x_template.shape[0]) // 2 pad_vert0 = (x_target.shape[0] - x_template.shape[0]) - pad_vert1 pad_horiz1 = (x_target.shape[1] - x_template.shape[1]) // 2 pad_horiz0 = (x_target.shape[1] - x_template.shape[1]) - pad_horiz1 pad_shape = [[pad_vert0, pad_vert1], [pad_horiz0, pad_horiz1]]

x_template_padded = np.pad(x_template, pad_shape)

assert x_template_padded.shape == x_target.shape plt.imshow(np.abs(x_template_padded), cmap='turbo'); plt.show()

OverLordGoldDragon
  • 8,912
  • 5
  • 23
  • 74