用Python编写实现图像的二维傅里叶变换的代码
时间: 2023-06-01 20:07:20 浏览: 58
以下是 Python 实现二维傅里叶变换的代码:
```python
import numpy as np
import cv2
# 读入图像
img = cv2.imread('image.jpg', 0)
# 二维傅里叶变换
f = np.fft.fft2(img)
# 平移直流分量到图像中心
fshift = np.fft.fftshift(f)
# 取模得到幅值图像
magnitude_spectrum = 20 * np.log(np.abs(fshift))
# 显示原始图像和傅里叶变换后的图像
cv2.imshow('Input Image', img)
cv2.imshow('Magnitude Spectrum', magnitude_spectrum.astype(np.uint8))
cv2.waitKey(0)
cv2.destroyAllWindows()
```
以上代码可以将图片进行二维傅里叶变换,并显示傅里叶变换后的幅值图像。
相关问题
用python编写实现图像的二维傅里叶变换的代码
以下是用Python编写实现图像二维傅里叶变换的代码:
```
import numpy as np
import cv2
# Load the image
img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
# Compute the 2D Fourier transform of the image
f = np.fft.fft2(img)
# Shift the zero-frequency component to the center of the spectrum
fshift = np.fft.fftshift(f)
# Compute the magnitude spectrum of the Fourier transform
magnitude_spectrum = 20*np.log(np.abs(fshift))
# Display the original image and the magnitude spectrum
cv2.imshow('Image', img)
cv2.imshow('Magnitude Spectrum', magnitude_spectrum)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,`cv2.imread`用于加载图像,`cv2.IMREAD_GRAYSCALE`指定图像读取为灰度图像;`np.fft.fft2`计算二维傅里叶变换,`np.fft.fftshift`将零频率分量移动到频谱的中心;`np.abs`计算复数的模,`20*np.log`将模数变换到对数域。最后,使用`cv2.imshow`显示原始图像和傅里叶变换后的幅度谱。
python实现图像二维傅里叶变换的代码
以下是 Python 实现图像二维傅里叶变换的代码:
```Python
import cv2
import numpy as np
img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE) # 读入灰度图像
dft = cv2.dft(np.float32(img), flags = cv2.DFT_COMPLEX_OUTPUT) # DFT
dft_shift = np.fft.fftshift(dft) # 将低频分量移到中心
magnitude_spectrum = 20*np.log(cv2.magnitude(dft_shift[:, :, 0], dft_shift[:, :, 1])) # 频谱图像的幅度谱
cv2.imshow('Input Image', img)
cv2.imshow('Magnitude Spectrum', magnitude_spectrum.astype(np.uint8))
cv2.waitKey()
cv2.destroyAllWindows()
```
这段代码会读取名为 `image.jpg` 的图像,并对其进行二维傅里叶变换,然后将频谱图像的幅度谱进行对数变换并显示出来。如果要对图像进行反变换,可以使用以下代码:
```Python
idft_shift = np.fft.ifftshift(dft_shift) # 将频域图像移到左上角
idft = cv2.idft(idft_shift) # IDFT
img_back = cv2.magnitude(idft[:, :, 0], idft[:, :, 1]) # 幅度谱的反变换
cv2.imshow('Reconstructed Image', img_back.astype(np.uint8))
cv2.waitKey()
cv2.destroyAllWindows()
```
这段代码将对调整过的频域图像进行反变换,得到原图像的幅度谱。最后将其显示出来。