Skip to content

Instantly share code, notes, and snippets.

@stefanherdy
Last active October 11, 2023 18:36
Show Gist options
  • Save stefanherdy/c05e4bc106f2791b29a979f1ccd1b039 to your computer and use it in GitHub Desktop.
Save stefanherdy/c05e4bc106f2791b29a979f1ccd1b039 to your computer and use it in GitHub Desktop.
Perform High Pass Filtering and Fast Fourier Transformation to show sharp parts of an image.
#!/usr/bin/python
"""
Script Name: fft.py
Author: Stefan Herdy
Date: 06.02.2021
Description:
This script performs high pass filtering and fast fourier transformation (fft) to show sharp parts of an image.
Usage:
- change the image name/ image path and run the script
"""
import cv2
import numpy as np
from matplotlib import pyplot as plt
# Load test image
# Replace image name with your image name
img = cv2.imread('./test.JPG',0)
# Perform Fast Fourier Transformation
f = np.fft.fft2(img)
fshift = np.fft.fftshift(f)
magnitude_spectrum = 20*np.log(np.abs(fshift))
# Plot Input image and Magnitude Spectrum
plt.subplot(121),plt.imshow(img, cmap = 'gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(magnitude_spectrum, cmap = 'gray')
plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
plt.show()
# Perform High Pass Filter operation
rows, cols = img.shape
crow,ccol = int(rows/2) , int(cols/2)
fshift[crow-500:crow+500, ccol-500:ccol+500] = 0
# Alternative High Pass Function:
# highpass=1-np.exp(- ((X-0.5)**2+(Y-0.5)**2)*5)
# fshift = fshift+highpass
f_ishift = np.fft.ifftshift(fshift)
img_back = np.fft.ifft2(f_ishift)
img_back = np.abs(img_back)
plt.subplot(131),plt.imshow(img, cmap = 'gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(132),plt.imshow(img_back, cmap = 'gray')
plt.title('Image after HPF'), plt.xticks([]), plt.yticks([])
plt.subplot(133),plt.imshow(img_back)
plt.title('Result in JET'), plt.xticks([]), plt.yticks([])
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment