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
from imageio import imread
import scipy
from scipy import signal
from scipy import misc

def pad_with(vector, pad_width, iaxis, kwargs):
    pad_value = kwargs.get('padder', 0)
    vector[:pad_width[0]] = pad_value
    vector[-pad_width[1]:] = pad_value

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

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

kernel = pad_to_shape(kernel, np.shape(sequence))

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.

enter image description here

  • $\begingroup$ 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. $\endgroup$ Oct 20 '21 at 22:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.