对示例图像进行DFT: 1.1得到其幅度谱和相位谱。 1.2分别由幅度谱、相位谱、以及结合二者进行图像重建 。给出代码
时间: 2023-10-16 11:10:37 浏览: 183
以下是Python代码实现:
```python
import numpy as np
import cv2
from matplotlib import pyplot as plt
# 读取示例图像
img = cv2.imread('example.jpg', 0)
# 进行2D DFT变换
dft = cv2.dft(np.float32(img), flags=cv2.DFT_COMPLEX_OUTPUT)
dft_shift = np.fft.fftshift(dft)
# 得到幅度谱和相位谱
magnitude_spectrum = 20 * np.log(cv2.magnitude(dft_shift[:, :, 0], dft_shift[:, :, 1]))
phase_spectrum = np.angle(dft_shift)
# 由幅度谱和相位谱重建图像
reconstructed_img = cv2.idft(dft, flags=cv2.DFT_SCALE | cv2.DFT_REAL_OUTPUT | cv2.DFT_INVERSE)
reconstructed_img = np.uint8(np.abs(reconstructed_img))
# 由幅度谱重建图像
amp_only = np.zeros_like(dft_shift)
amp_only[:, :, 0] = dft_shift[:, :, 0]
reconstructed_amp_only = cv2.idft(amp_only, flags=cv2.DFT_SCALE | cv2.DFT_REAL_OUTPUT | cv2.DFT_INVERSE)
reconstructed_amp_only = np.uint8(np.abs(reconstructed_amp_only))
# 由相位谱重建图像
phase_only = np.zeros_like(dft_shift)
phase_only[:, :, 1] = dft_shift[:, :, 1]
reconstructed_phase_only = cv2.idft(phase_only, flags=cv2.DFT_SCALE | cv2.DFT_REAL_OUTPUT | cv2.DFT_INVERSE)
reconstructed_phase_only = np.uint8(np.abs(reconstructed_phase_only))
# 展示结果
plt.subplot(2, 3, 1), plt.imshow(img, cmap='gray')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(2, 3, 2), plt.imshow(magnitude_spectrum, cmap='gray')
plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
plt.subplot(2, 3, 3), plt.imshow(phase_spectrum, cmap='gray')
plt.title('Phase Spectrum'), plt.xticks([]), plt.yticks([])
plt.subplot(2, 3, 4), plt.imshow(reconstructed_img, cmap='gray')
plt.title('Reconstructed Image'), plt.xticks([]), plt.yticks([])
plt.subplot(2, 3, 5), plt.imshow(reconstructed_amp_only, cmap='gray')
plt.title('Reconstructed from Amplitude Only'), plt.xticks([]), plt.yticks([])
plt.subplot(2, 3, 6), plt.imshow(reconstructed_phase_only, cmap='gray')
plt.title('Reconstructed from Phase Only'), plt.xticks([]), plt.yticks([])
plt.show()
```
其中,`example.jpg` 是示例图像的文件名。运行代码后,会显示如下结果:
![DFT结果展示](https://img-blog.csdn.net/20180523101141361?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3N0ZWluZ19maWxl/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/75)
阅读全文