Fourier transform in OpenCV

Fourier transform (FT) is a very important image processing tool, which is used to decompose the image into frequency components. The output of FT represents the image in the frequency domain, while the output image is equivalent to the spatial domain (x, y). In the frequency domain image, each point represents a specific frequency contained in the spatial domain. Therefore, for images with many high frequency components (edges, corners and stripes), the frequency value of many points in the frequency domain will be very high.
Here is the code for the Fourier transform:

import numpy as np
import matplotlib.pyplot as plt
import cv2

%matplotlib inline

#Read in the images
image_stripes = cv2.imread('images/stripes.jpg')
#Change color to RGB (from BGR)
image_stripes = cv2.cvtColor(image_stripes, cv2.COLOR_BGR2RGB)

#Read in the images
image_solid = cv2.imread('images/pink_solid.jpg')
#Change color to RGB (from BGR)
image_solid = cv2.cvtColor(image_solid, cv2.COLOR_BGR2RGB)


#Display the images
f, (ax1,ax2) = plt.subplots(1, 2, figsize=(10,5))

ax1.imshow(image_stripes)
ax2.imshow(image_solid)
#convert to grayscale to focus on the intensity patterns in the image
gray_stripes = cv2.cvtColor(image_stripes, cv2.COLOR_RGB2GRAY)
gray_solid = cv2.cvtColor(image_solid, cv2.COLOR_RGB2GRAY)

#normalize the image color values from a range of [0,255] to [0,1] for further processing
norm_stripes = gray_stripes/255.0
norm_solid = gray_solid/255.0

#perform a fast fourier transform and create a scaled, frequency transform image
def ft_image(norm_image):
    f = np.fft.fft2(norm_image)
    fshift = np.fft.fftshift(f)  ### Move results to the center of the screen
    frequency_tx = 20*np.log(np.abs(fshift)) ## Calculation formula of amplitude spectrum
    return frequency_tx   
# Call the function on the normalized images
# and display the transforms
f_stripes = ft_image(norm_stripes)
f_solid = ft_image(norm_solid)

# display the images
# original images to the left of their frequency transform
f, (ax1,ax2,ax3,ax4) = plt.subplots(1, 4, figsize=(20,10))

ax1.set_title('original image')
ax1.imshow(image_stripes)
ax2.set_title('frequency transform image')
ax2.imshow(f_stripes, cmap='gray')

ax3.set_title('original image')
ax3.imshow(image_solid)
ax4.set_title('frequency transform image')
ax4.imshow(f_solid, cmap='gray')

Original image:

Design sketch:

Added by mbdonner on Sat, 30 Nov 2019 11:51:39 +0200