基于卷积神经网络的图像降噪python代码
时间: 2023-10-18 15:03:07 浏览: 134
毕业设计-基于Python+卷积神经网络的人脸识别+驾驶员疲劳检测与预警系统的设计与实现+PyQt5 + OpenCV
5星 · 资源好评率100%
基于卷积神经网络的图像降噪的Python代码:
首先,我们需要导入所需的模块:
```python
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D
from tensorflow.keras.models import Sequential
from tensorflow.keras.datasets import mnist
```
接下来,我们定义一个卷积神经网络模型:
```python
def create_model():
model = Sequential()
model.add(Conv2D(16, (3, 3), activation='relu', padding='same', input_shape=(28, 28, 1)))
model.add(MaxPooling2D((2, 2), padding='same'))
model.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D((2, 2), padding='same'))
model.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D((2, 2), padding='same'))
model.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model.add(UpSampling2D((2, 2)))
model.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model.add(UpSampling2D((2, 2)))
model.add(Conv2D(16, (3, 3), activation='relu', padding='same'))
model.add(UpSampling2D((2, 2)))
model.add(Conv2D(1, (3, 3), activation='sigmoid', padding='same'))
return model
```
接下来,我们加载MNIST数据集,并对图像进行预处理:
```python
(x_train, _), (x_test, _) = mnist.load_data()
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = np.reshape(x_train, (len(x_train), 28, 28, 1))
x_test = np.reshape(x_test, (len(x_test), 28, 28, 1))
# 添加高斯噪声
noise_factor = 0.5
x_train_noisy = x_train + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_train.shape)
x_test_noisy = x_test + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_test.shape)
x_train_noisy = np.clip(x_train_noisy, 0., 1.)
x_test_noisy = np.clip(x_test_noisy, 0., 1.)
```
现在,我们创建并编译模型,并进行训练:
```python
model = create_model()
model.compile(optimizer='adam', loss='binary_crossentropy')
model.fit(x_train_noisy, x_train, epochs=10, batch_size=128, shuffle=True, validation_data=(x_test_noisy, x_test))
```
训练完成后,我们可以使用模型对测试集进行预测,并输出降噪后的图像:
```python
decoded_imgs = model.predict(x_test_noisy)
import matplotlib.pyplot as plt
n = 10 # 要显示的图像数量
plt.figure(figsize=(20, 4))
for i in range(n):
# 原始图像
ax = plt.subplot(2, n, i + 1)
plt.imshow(x_test_noisy[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# 降噪后图像
ax = plt.subplot(2, n, i + 1 + n)
plt.imshow(decoded_imgs[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
```
这段代码实现了基于卷积神经网络的图像降噪。我们首先定义了一个包含多个卷积层和上采样层的模型,然后加载MNIST数据集,并在训练数据上添加高斯噪声。接下来,我们创建并编译模型,并使用训练数据进行训练。最后,我们使用训练好的模型对测试数据进行预测,并展示降噪后的图像。
阅读全文