Fourier Transform of an image using OpenCV Python

Fourier Transform

The Fourier Transform is a powerful tool in image processing, converting spatial data into frequency data. This technique is useful for various applications, such as image filtering, image compression, and noise reduction. In this article, we will explore how to apply the Fourier Transform to an image using OpenCV in Python. We will provide detailed coding examples to help you understand the process.

Prerequisites

Before we begin, ensure you have the following libraries installed:

You can install them using pip if you haven’t already:

pip install opencv-python-headless numpy matplotlib

Let us see now how it works,

Step-by-Step Implementation

Step 1: Import Libraries

First, import the necessary libraries.

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

Step 2: Read and Display the Image
Read an image using OpenCV and display it using Matplotlib.

# Read the image in grayscale mode
image = cv2.imread('path_to_your_image.jpg', cv2.IMREAD_GRAYSCALE)

# Display the original image
plt.figure(figsize=(6, 6))
plt.title("Original Image")
plt.imshow(image, cmap='gray')
plt.axis('off')
plt.show()

Step 3: Apply Fourier Transform
Use the cv2.dft() function to apply the Discrete Fourier Transform (DFT) to the image.

# Apply DFT
dft = cv2.dft(np.float32(image), flags=cv2.DFT_COMPLEX_OUTPUT)

# Shift the zero frequency component to the center
dft_shift = np.fft.fftshift(dft)

# Compute the magnitude spectrum
magnitude_spectrum = 20 * np.log(cv2.magnitude(dft_shift[:, :, 0], dft_shift[:, :, 1]))

# Display the magnitude spectrum
plt.figure(figsize=(6, 6))
plt.title("Magnitude Spectrum")
plt.imshow(magnitude_spectrum, cmap='gray')
plt.axis('off')
plt.show()

Step 4: Apply Inverse Fourier Transform
To verify our results, we can apply the Inverse Fourier Transform and reconstruct the original image.

# Shift the zero frequency component back to the original place
dft_ishift = np.fft.ifftshift(dft_shift)

# Apply Inverse DFT
image_back = cv2.idft(dft_ishift)
image_back = cv2.magnitude(image_back[:, :, 0], image_back[:, :, 1])

# Normalize the image for display
cv2.normalize(image_back, image_back, 0, 1, cv2.NORM_MINMAX)

# Display the reconstructed image
plt.figure(figsize=(6, 6))
plt.title("Reconstructed Image")
plt.imshow(image_back, cmap='gray')
plt.axis('off')
plt.show()

Full Code:

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

def fourier_transform_image(image_path):
    # Step 1: Read the image in grayscale mode
    image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

    # Step 2: Display the original image
    plt.figure(figsize=(12, 6))
    plt.subplot(1, 3, 1)
    plt.title("Original Image")
    plt.imshow(image, cmap='gray')
    plt.axis('off')

    # Step 3: Apply DFT
    dft = cv2.dft(np.float32(image), flags=cv2.DFT_COMPLEX_OUTPUT)

    # Shift the zero frequency component to the center
    dft_shift = np.fft.fftshift(dft)

    # Compute the magnitude spectrum
    magnitude_spectrum = 20 * np.log(cv2.magnitude(dft_shift[:, :, 0], dft_shift[:, :, 1]))

    # Display the magnitude spectrum
    plt.subplot(1, 3, 2)
    plt.title("Magnitude Spectrum")
    plt.imshow(magnitude_spectrum, cmap='gray')
    plt.axis('off')

    # Step 4: Apply Inverse DFT
    dft_ishift = np.fft.ifftshift(dft_shift)
    image_back = cv2.idft(dft_ishift)
    image_back = cv2.magnitude(image_back[:, :, 0], image_back[:, :, 1])

    # Normalize the image for display
    cv2.normalize(image_back, image_back, 0, 1, cv2.NORM_MINMAX)

    # Display the reconstructed image
    plt.subplot(1, 3, 3)
    plt.title("Reconstructed Image")
    plt.imshow(image_back, cmap='gray')
    plt.axis('off')

    plt.show()

# Provide the path to your image
image_path = 'Dhoni.jpg'
fourier_transform_image(image_path)

Output:

Explanation

  1. import cv2: This imports the OpenCV library, which is used for image processing.
  2. import numpy as np: This imports the NumPy library and aliases it as np. NumPy is used for numerical operations on arrays.
  3. import matplotlib.pyplot as plt: This imports the pyplot module from Matplotlib and aliases it as plt. Matplotlib is used for plotting graphs and images.
  4. def fourier_transform_image(image_path): This defines a function named fourier_transform_image that takes one parameter, image_path, which is the path to the image file.
  5. image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE): This reads the image from the specified path in grayscale mode using OpenCV’s imread function. The flag cv2.IMREAD_GRAYSCALE converts the image to grayscale.
  6. plt.figure(figsize=(12, 6)): This creates a new figure with a specified size of 12×6 inches for plotting.
  7. plt.subplot(1, 3, 1): This creates a subplot layout with 1 row and 3 columns and selects the first subplot for plotting.
  8. plt.title("Original Image"): This sets the title of the first subplot to “Original Image”.
  9. plt.imshow(image, cmap='gray'): This displays the grayscale image in the first subplot. The cmap='gray' argument ensures the image is shown in grayscale.
  10. plt.axis('off'): This turns off the axis lines and labels for the subplot.
  11. dft = cv2.dft(np.float32(image), flags=cv2.DFT_COMPLEX_OUTPUT): This applies the Discrete Fourier Transform (DFT) to the image using OpenCV’s dft function. The image is first converted to float32 format, and the flags=cv2.DFT_COMPLEX_OUTPUT flag ensures the output is a complex number with two channels representing the real and imaginary parts.
  12. dft_shift = np.fft.fftshift(dft): This shifts the zero frequency component to the center of the spectrum using NumPy’s fftshift function. This makes the visualization of the frequency components easier.
  13. magnitude_spectrum = 20 * np.log(cv2.magnitude(dft_shift[:, :, 0], dft_shift[:, :, 1])): This computes the magnitude spectrum of the DFT. The cv2.magnitude function calculates the magnitude of the complex numbers from the real and imaginary parts. The logarithm (scaled by 20) is applied to enhance the visualization of the spectrum.
  14. plt.subplot(1, 3, 2): This selects the second subplot for plotting.
  15. plt.title("Magnitude Spectrum"): This sets the title of the second subplot to “Magnitude Spectrum”.
  16. plt.imshow(magnitude_spectrum, cmap='gray'): This displays the magnitude spectrum in the second subplot.
  17. plt.axis('off'): This turns off the axis lines and labels for the subplot.
  18. dft_ishift = np.fft.ifftshift(dft_shift): This shifts the zero frequency component back to its original position using NumPy’s ifftshift function.
  19. image_back = cv2.idft(dft_ishift): This applies the Inverse DFT to convert the frequency data back to the spatial domain using OpenCV’s idft function.
  20. image_back = cv2.magnitude(image_back[:, :, 0],
  21. image_back[:, :, 1]): This computes the magnitude of the inverse DFT result to obtain the reconstructed image.
  22. cv2.normalize(image_back, image_back, 0, 1, cv2.NORM_MINMAX): This normalizes the reconstructed image to the range [0, 1] using OpenCV’s normalize function. The cv2.NORM_MINMAX flag ensures the minimum and maximum values in the array are scaled to 0 and 1, respectively.
  23. plt.subplot(1, 3, 3): This selects the third subplot for plotting.
  24. plt.title("Reconstructed Image"): This sets the title of the third subplot to “Reconstructed Image”.
  25. plt.imshow(image_back, cmap='gray'): This displays the normalized reconstructed image in the third subplot.
  26. plt.axis('off'): This turns off the axis lines and labels for the subplot.
  27. plt.show(): This displays all the subplots.
  28. image_path = 'Dhoni.jpg': This sets the path to the image file.
  29. fourier_transform_image(image_path): This calls the fourier_transform_image function with the specified image path to execute the entire Fourier Transform process and display the results.

Conclusion
In this article, we demonstrated how to apply the Fourier Transform to an image using OpenCV in Python. We covered the process of reading an image, applying the DFT, visualizing the magnitude spectrum, and reconstructing the original image using the Inverse DFT. This technique is fundamental in image processing and has numerous applications in various fields.

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>