🐍 Python & library/PyTorch

Numpy & PyTorch로 2D fourier transform, inverse fourier transform하기

복만 2022. 8. 27. 16:08

사용할 이미지

dog.jpg

 

 

Load image

import cv2
import matplotlib.pyplot as plt

img = cv2.imread('dog.jpg', cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (256, 256))

print(img.shape)
plt.imshow(img, cmap='gray')
plt.colorbar()

(256, 256)

 

 

FFT and IFFT using numpy

import numpy as np

fft_img = np.fft.fftshift(np.fft.fft2(img, norm='ortho'))

print(fft_img.shape, fft_img.dtype)
plt.imshow(np.abs(fft_img), cmap='gray')
plt.colorbar()

(256, 256) complex128

 

ifft_img = np.fft.ifft2(np.fft.ifftshift(fft_img), norm='ortho')

print(ifft_img.shape, ifft_img.dtype)
plt.imshow(np.abs(ifft_img), cmap='gray')
plt.colorbar()

(256, 256) complex 128

 

 

FFT and IFFT using PyTorch

import torch

tensor = torch.from_numpy(img)

fft_tensor = torch.fft.fftshift(torch.fft.fft2(tensor, norm='ortho'))

print(fft_tensor.shape, fft_tensor.dtype)
plt.imshow(torch.abs(fft_tensor), cmap='gray')
plt.colorbar()

torch.size([256, 256]) torch.complex64

 

ifft_tensor = torch.fft.ifft2(torch.fft.ifftshift(fft_tensor), norm='ortho')

print(ifft_tensor.shape, ifft_tensor.dtype)
plt.imshow(torch.abs(ifft_tensor), cmap='gray')
plt.colorbar()

torch.size([256, 256]) torch.complex64

반응형