# FFT filtering by hand in python - iffy issue - cannot get filtering right

I am trying to filter an image by hand (with no using the image processing libraries) to understand how fft.shift works in python. No luck. I take a png an image from MNIST, e.g.. Here is the code:

import numpy as np
import matplotlib.pyplot as plt
import math
import glob, os
import scipy
from scipy import signal
from scipy import misc

kernel = np.array([[-1, -1, -1],
[-1,  8, -1],
[-1, -1, -1]])

threshold = 150
sequence = 1.0 * (sequence > threshold)\

f = np.fft.fft2(sequence)
f_shifted = np.fft.fftshift(f)
f_filtered = kernel * f_shifted

f_filtered_shifted = np.fft.fftshift(f_filtered)
inv_img = np.fft.ifft2(f_filtered_shifted) # inverse F.T.
filtered_img = np.abs(inv_img)
filtered_img -= filtered_img.min()
filtered_img = filtered_img*255 / filtered_img.max()
filtered_img = filtered_img.astype(np.uint8)


I must be missing something as it produces garbage.

• You need to take the FFT of the kernel too. And you need to make sure that the origin of the kernel is at (0,0) (top-left corner) after padding and before FFTing. And you shouldn’t take the abs of the IFFT, because the result of the Laplacian filter has negative values that you need to preserve. Take the real component instead. Oct 20 '21 at 22:06