读取一幅图像,为该图像添加噪声(噪声类型、噪声参数自选),利用逆滤波对该图像进行复原,输出原图像、噪声图像、复原后图像,
时间: 2024-02-06 21:02:04 浏览: 19
好的,以下是我对您的问题的回答:
首先,我们需要导入相关的库:cv2(OpenCV)、numpy 和 matplotlib。
```python
import cv2
import numpy as np
import matplotlib.pyplot as plt
```
接下来,我们读取一幅图像。这里我使用的是 OpenCV 自带的 lena 图像。
```python
img = cv2.imread("lena.jpg", cv2.IMREAD_GRAYSCALE)
```
然后,我们为该图像添加噪声。这里我选择使用高斯噪声,噪声参数为均值为 0,标准差为 30。
```python
mean = 0
std = 30
noise = np.random.normal(mean, std, img.shape)
noisy_img = img + noise
```
现在我们有了噪声图像,接下来我们可以使用逆滤波对该图像进行复原。逆滤波需要知道噪声的功率谱密度函数和原图像的功率谱密度函数。这里我们可以使用傅里叶变换来获取这两个函数。
```python
f = np.fft.fft2(noisy_img)
fshift = np.fft.fftshift(f)
magnitude_spectrum = 20 * np.log(np.abs(fshift))
psd_noise = np.abs(fshift) ** 2
psd_img = np.abs(np.fft.fft2(img)) ** 2
```
接下来,我们可以计算出逆滤波的核函数。
```python
kernel = psd_img / psd_noise
kernel = np.where(kernel < 0.1, 0, kernel)
```
然后,我们可以使用逆滤波进行复原。
```python
fshift = fshift * kernel
fshift = np.fft.ifftshift(fshift)
ifft = np.fft.ifft2(fshift)
restored_img = np.abs(ifft)
```
最后,我们可以将原图像、噪声图像和复原后图像输出并展示。
```python
plt.subplot(131), plt.imshow(img, cmap="gray")
plt.title("Original Image"), plt.xticks([]), plt.yticks([])
plt.subplot(132), plt.imshow(noisy_img, cmap="gray")
plt.title("Noisy Image"), plt.xticks([]), plt.yticks([])
plt.subplot(133), plt.imshow(restored_img, cmap="gray")
plt.title("Restored Image"), plt.xticks([]), plt.yticks([])
plt.show()
```
完整代码如下:
```python
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread("lena.jpg", cv2.IMREAD_GRAYSCALE)
mean = 0
std = 30
noise = np.random.normal(mean, std, img.shape)
noisy_img = img + noise
f = np.fft.fft2(noisy_img)
fshift = np.fft.fftshift(f)
magnitude_spectrum = 20 * np.log(np.abs(fshift))
psd_noise = np.abs(fshift) ** 2
psd_img = np.abs(np.fft.fft2(img)) ** 2
kernel = psd_img / psd_noise
kernel = np.where(kernel < 0.1, 0, kernel)
fshift = fshift * kernel
fshift = np.fft.ifftshift(fshift)
ifft = np.fft.ifft2(fshift)
restored_img = np.abs(ifft)
plt.subplot(131), plt.imshow(img, cmap="gray")
plt.title("Original Image"), plt.xticks([]), plt.yticks([])
plt.subplot(132), plt.imshow(noisy_img, cmap="gray")
plt.title("Noisy Image"), plt.xticks([]), plt.yticks([])
plt.subplot(133), plt.imshow(restored_img, cmap="gray")
plt.title("Restored Image"), plt.xticks([]), plt.yticks([])
plt.show()
```