0
0
SciPydata~5 mins

2D FFT (fft2) in SciPy

Choose your learning style9 modes available
Introduction

2D FFT helps us find patterns and frequencies in images or 2D data. It changes data from space view to frequency view.

Analyzing textures or repeating patterns in images.
Filtering noise from 2D signals like photos or sensor data.
Compressing images by focusing on important frequency parts.
Detecting edges or shapes by looking at frequency changes.
Syntax
SciPy
scipy.fft.fft2(input_array, s=None, axes=(-2, -1), norm=None)

input_array is your 2D data (like an image).

s lets you set the shape of the FFT output (optional).

Examples
Basic 2D FFT on a 2x2 array.
SciPy
from scipy.fft import fft2
import numpy as np

arr = np.array([[1, 2], [3, 4]])
result = fft2(arr)
FFT with output size padded or trimmed to 4x4.
SciPy
result = fft2(arr, s=(4,4))
Specifying axes explicitly for 2D FFT.
SciPy
result = fft2(arr, axes=(0,1))
Sample Program

This program shows how to use 2D FFT on a simple 4x4 pattern. It prints the original image, the magnitude of frequency data, and the recovered image after inverse FFT.

SciPy
from scipy.fft import fft2, ifft2
import numpy as np

# Create a simple 4x4 image with a pattern
image = np.array([
    [1, 2, 1, 2],
    [3, 4, 3, 4],
    [1, 2, 1, 2],
    [3, 4, 3, 4]
])

# Compute 2D FFT
freq_data = fft2(image)

# Compute inverse FFT to get back original image
recovered_image = ifft2(freq_data)

# Print original, frequency magnitude, and recovered image
print("Original Image:\n", image)
print("\nFrequency Magnitude:\n", np.abs(freq_data))
print("\nRecovered Image (rounded):\n", np.round(recovered_image.real).astype(int))
OutputSuccess
Important Notes

FFT output is complex numbers showing amplitude and phase of frequencies.

Use np.abs() to get magnitude (strength) of frequencies.

Inverse FFT (ifft2) recovers original data from frequency data.

Summary

2D FFT changes 2D data into frequency space to find patterns.

It is useful for image and signal analysis.

Use scipy.fft.fft2 to apply 2D FFT and ifft2 to reverse it.