I tried to implement a Frequency Domain Laplacian Filterion Python according to this formula, which I found from a lecture note:
This is my Python function:
import numpy as np
from matplotlib import pyplot as plt
# The function takes two dimension inputs for the filter image;
def highLaplacian(M, N):
# Initializing the filter with ones; since the filter is a complex function,
# it has two channels, representing the real and imaginary parts;
# the data type is float32, since the pixels will take floating point values:
filter = np.zeros((M, N, 2), dtype=np.float32)
# Scanning through each pixel and calculating the negative of the sum of the
# squares of the pixels, and assigning the value to the corresponding pixel
# in the filter:
for i in range(M):
for j in range(N):
filter[i][j] = -(i**2 + j**2)
return filter
When I use this filter on an image which is transferred to the Fourier Domain, the output image does not change. I successfully implemented Ideal High Pass, Butterworth High Pass, and Gaussian High Pass filters from this lecture in which I used for Laplacian Filter. However I do not understand why it did not work for the Laplacian.
This is the main file which uses the Laplacian Filter on a Fourier Domain image:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread("airfield-05small-auto.tif")
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
m, n = img.shape
ft = cv2.dft(np.float32(img), flags=cv2.DFT_COMPLEX_OUTPUT)
ft_shifted = dft_shift = np.fft.fftshift(ft)
filter = highLaplacian(m, n)
filterMag = 20 * np.log(cv2.magnitude(filter[:, :, 0], filter[:, :, 1]))
applied = ft_shifted * filter
fshift_mask_mag = 20 * np.log(cv2.magnitude(applied[:, :, 0], applied[:, :, 1]))
f_ishift = np.fft.ifftshift(applied)
img_back = cv2.idft(f_ishift)
img_back = cv2.magnitude(img_back[:, :, 0], img_back[:, :, 1])
imgplot = plt.imshow(img_back, cmap="gray")
plt.show()
cv2.imwrite("lap_output.png", filterMag)
The issue is that your filter needs to be centered in the middle of the image. So you need
filter[i][j] = -((i-M/2)**2 + (j-N/2)**2)
which then produces:
and the filter looks as follows: