# Restoration problem with numpy fft function and self-made high-pass filter

Hi, I am using numpy.fft functions to do CV assignments in univ. But while implementing the high-pass and low-pass filter, I found something wrong during the process. The difference should converge near zero after naively restore the image but it doesn't. What I did are:

1. I got filtered images by ( fft2 -> fftshift -> apply filter -> ifftshift -> ifft2 ). (Filters are low-pass and high-pass)
2. With this filtered image, I just simply applied fourier transform and restore it without doing anything.
3. However, there are huge difference between the filtered image and restored one.
import numpy as np
import cv2

def high_pass_filter(img, th=30):
r, c = img.shape
y, x = np.mgrid[:r, :c]
hp_filter = np.where(np.sqrt((y - r // 2) ** 2 + (x - c // 2) ** 2) <= th, 0, 1)
filtered = np.fft.fftshift(np.fft.fft2(img)) * hp_filter
filtered = np.fft.ifftshift(filtered)
res = abs(np.fft.ifft2(filtered))
return res

def low_pass_filter(img, th=30):
r, c = img.shape
y, x = np.mgrid[:r, :c]
lp_filter = np.where(np.sqrt((y-r//2)**2 + (x-c//2)**2) <= th, 1, 0)
filtered = np.fft.fftshift(np.fft.fft2(img)) * lp_filter
filtered = np.fft.ifftshift(filtered)
res = abs(np.fft.ifft2(filtered))
return res

fshift = np.fft.fftshift(np.fft.fft2(img))
res = np.fft.ifft2(np.fft.ifftshift(fshift))
print((img-res).sum())

h_img = high_pass_filter(img)
fshift = np.fft.fftshift(np.fft.fft2(h_img))
res = np.fft.ifft2(np.fft.ifftshift(fshift))
print((img-res).sum())

l_img = low_pass_filter(img)
fshift = np.fft.fftshift(np.fft.fft2(l_img))
res = np.fft.ifft2(np.fft.ifftshift(fshift))
print((img-res).sum())



Below are the results.

(-1.0800249583553523e-12+1.8932661725304283e-29j)

(52375+0j)

(-1.6768808563938364e-12-1.262177448353619e-29j)

As you can see, original image and low-passed image are restored well, but high-passed filter has huge difference. What's wrong did I have?