去噪声自动编解码(附keras实现)


前言

       自动编解码网络是一种较为独特的神经网络,它分成编码网络和解码网络两个部分。从功能上看,编码网络是将输入的数据转为一组张量,而解码网络可以将张量还原出原来的数据。自动编解码网络作为一种无监督学习的模型,但实际使用时一般都是在图像处理某个领域,一般做监督学习模型,在训练需要对输入数据根据所需情况进行一定的处理。如今自动编解码网络也是广泛应用在图像复原,图像去噪,图像上色等等领域,其间的算法结构也衍生了生成对抗模型。


一、去噪声自动编解码

        去噪声自编码网络其实就是自编码网络的其中一个应用模型,因为自编码网络只是还原了原来的图像,在实际应用上意义不大。但是基于自编码网络却衍生了众多的有实际应用的模型,去噪声自动编解码模型便是其中一种,同时因为编解码过程中,因其数据变化的特点,也被人常用做正则化编码器,可用以提高模型的泛化能力及鲁棒性。大致结构如下图,当然也有通过其他实现方式,本文将通过搭建多个卷积层和反卷积层,BN层实现。

二、构建模型

模型结构如下:

1.引入库

from keras.callbacks import Callback
from keras.layers import Input
from keras.layers import Conv2D, BatchNormalization
from keras.layers import Conv2DTranspose
from keras.models import Model
import numpy as np
import matplotlib.pyplot as plt

2.读入数据

def getImageData(base_position='Corel5k/', imgwidth=128, imgheight=128):
    '''
    从数据集中获取图像信息
    输出训练集图像矩阵,测试集图像矩阵,(0-1)
    '''
    imgtrain_position = []
    imgtest_position = []
    training_image = []
    testing_image = []
    #获取文件名
    for line in open(imgtrain_file, 'r'):
        imgtrain_position.append(base_position + line[:-1] +'.jpeg')
    for line in open(imgtest_file, 'r'):
        imgtest_position.append(base_position + line[:-1] + '.jpeg')
    #读取图像,做归一化
    for i in range(len(imgtrain_position)):
        train_image = (Image.open(imgtrain_position[i])).resize((imgwidth, imgheight))
        train_image = (np.asarray(train_image)).astype('float32') / 255.
        training_image.append(train_image)

    for i in range(len(imgtest_position)):
        test_image = (Image.open(imgtest_position[i])).resize((imgwidth, imgheight))
        test_image = (np.asarray(test_image)).astype('float32') / 255.
        testing_image.append(test_image)
    #转为数组
    training_image = np.array(training_image)
    testing_image = np.array(testing_image)
    return training_image, testing_image

 

3.模型训练

x_train, x_test = getImageData()
image_size = 128

input_shape = (image_size, image_size, 3)
batch_size = 50
kernel_size = 3

#加入噪声
noise_factor = 0.01
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)

#模型搭建
inputs = Input(shape=input_shape, name='encoder_input')
x = inputs

layer_filters = [64, 128, 128]
for filters in layer_filters:
    x = Conv2D(filters=filters, kernel_size=kernel_size, kernel_initializer='glorot_normal', activation='relu', strides=2, padding='same')(x)
    x = BatchNormalization(momentum=0.8)(x)

for filters in layer_filters[::-1]:
    x = Conv2DTranspose(filters=filters, kernel_size=kernel_size, kernel_initializer='glorot_normal', activation='relu', strides=2, padding='same')(x)

outputs = Conv2DTranspose(filters=3, kernel_size=kernel_size, activation='sigmoid', padding='same', name='decoder_output')(x)
decoder = Model(inputs, outputs, name='decoder')
decoder.summary()

autoencoder = Model(inputs, decoder(inputs), name='autoencoder')
autoencoder.summary()
autoencoder.compile(loss='mse', optimizer='adam')
#记录数据
history = LossHistory()
autoencoder.fit(x_train_noisy, x_train, validation_data=(x_test_noisy, x_test), epochs=50, batch_size=batch_size, callbacks=[history])
x_decoded = autoencoder.predict(x_test)
#保存模型
autoencoder.save('model.h5')

#预测8张图
imgs = np.concatenate([x_test_noisy[:8], x_decoded[:8]])
imgs = imgs.reshape((4, 4, image_size, image_size, 3))
imgs = np.vstack([np.hstack(i) for i in imgs])
np.save('gunloss.npy', history.losses)
plt.figure()
plt.axis('off')
plt.imshow(imgs, interpolation='none', cmap='gray')
plt.show()

三、实验结果

前8张为加入噪声的图片,后8张为经过模型生成的图片。可以看到基本可以达到去噪效果,且生成的图片也较为清晰。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值