Skip to content

Instantly share code, notes, and snippets.

@mocquin
Created July 20, 2023 12:09
Show Gist options
  • Save mocquin/0cecbdfd4003bbfed6c56320a091ba34 to your computer and use it in GitHub Desktop.
Save mocquin/0cecbdfd4003bbfed6c56320a091ba34 to your computer and use it in GitHub Desktop.
# from scipy.ndimage.convolve doc :
# > Each value in result is C_i = \sum_j{I_{i+k-j} W_j}, where
# W is the `weights` kernel,
# j is the N-D spatial index over :math:`W`,
# I is the `input` and k is the coordinate of the center of
# W, specified by `origin` in the input parameters.
# Hence we need to center the kernel
vpad = (V-N)//2+N%2, (V-N)//2
hpad = (H-N)//2+N%2, (H-N)//2
kernel_padded_centered = np.pad(kernel, (vpad, hpad))
kernel_padded_centered = np.fft.fftshift(kernel_padded_centered)
p_kernel_padded_centered = PeriodicArray(kernel_padded_centered)
fft_centered = np.fft.ifft2(np.fft.fft2(img) * np.fft.fft2(kernel_padded_centered))
p_fft_centered = PeriodicArray(fft_centered.real)
# check that we have identical results :
assert np.allclose(p_fft_centered.base, p_wrap.base)
# plot everything
fig, axes = plt.subplots(1, 3)
p_wrap.plot(ax=axes[0])
axes[0].set_title("scipy with mode='wrap'")
p_fft.plot(ax=axes[1])
axes[1].set_title("Fourier approach")
p_fft_centered.plot(ax=axes[2])
axes[2].set_title("Fourier approac \n with symmetric kernelh")
fig.tight_layout()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment