Two-dimensional FFT (FFT2)

Image FFT
Reading time: about 7 minutes

This page is about the 2D FFT, also called FFT2 in certain libraries and programming environments.

In [2]:
img = Image.open("/home/leo/kekw.jpg").convert('L')
#img = img.resize((int(img.width / 4), int(img.height / 4)))
In [3]:
npimg = np.zeros((img.height, img.width))

for y in range(img.height):
    for x in range(img.width):
        npimg[y][x] = img.getpixel((x, y))

npimg = npimg / 256
img = npimg
plt.imshow(img, cmap="gray")
plt.colorbar()
Out [3]:
Out [3]:
Out:
<Figure size 900x600 with 2 Axes>
In [4]:
def fft_rows(img):
    fft_img = np.zeros(img.shape, dtype=np.complex_)
    
    for y in range(img.shape[0]):
        row = [img[y][x] for x in range(img.shape[1])]
        
        row_fft = np.fft.fft(row)
        
        for x, col in enumerate(row_fft):
            fft_img[y][x] = col
        
    return fft_img

img = fft_rows(img)

plt.imshow(np.abs(img), vmax=1)
plt.colorbar()
Out [4]:
Out [4]:
Out:
<Figure size 900x600 with 2 Axes>
In [5]:
def fft_cols(img):
    fft_img = np.zeros(img.shape, dtype=np.complex_)
    
    for x in range(img.shape[1]):
        row = [img[y][x] for y in range(img.shape[0])]
        
        row_fft = np.fft.fft(row)
        
        for y, col in enumerate(row_fft):
            fft_img[y][x] = col
        
    return fft_img

img = fft_cols(img)

plt.imshow(np.abs(img), vmax=2)
plt.colorbar()
Out [5]:
Out [5]:
Out:
<Figure size 900x600 with 2 Axes>
In [6]:
plt.imshow(np.fft.ifft2(img).real, cmap="gray")
plt.colorbar()
Out [6]:
Out [6]:
Out:
<Figure size 900x600 with 2 Axes>
In [7]:
shp = img.shape
img = img.flatten()

decim = 50

for i, x in enumerate(img):
    img[i] = int(x.real / decim) * decim + int(x.imag / decim) * decim * 1j

img = img.reshape(shp)

plt.imshow(np.fft.ifft2(img).real, cmap="gray")
plt.colorbar()
Out [7]:
Out [7]:
Out: