Minifycode 2020-01-16 Viewed 1.3K times Artificial Intelligence (AI)
We need the following libraries for Denoising of image: 

from keras.datasets import mnist
import numpy as np
import matplotlib.pyplot as plt

from keras.layers import Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.models import Sequential
from keras import backend as K

First we have to load the data (here we load data from MNIST Database)
(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))


#For denoising of the image we will use Autoencoder (, Autoencoders is a Reinforcement learning.) & Bulid the CNN Model.
#code
input_img = (28, 28, 1)

model = Sequential()

model.add(Conv2D(16, (3, 3), activation='relu', padding='same', input_shape = input_img))
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'))

# at this point the representation is (4, 4, 8) i.e. 128-dimensional

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'))
model.add(UpSampling2D((2, 2)))

model.add(Conv2D(1, (3, 3), activation='sigmoid', padding='same'))

model.compile(optimizer='adam', 
              loss='binary_crossentropy', 
              metrics=['accuracy'])

model.summary()

# we will show the machine how the data look like(fit the model ,“hist-is a variable”)
hist = model.fit(x_train, x_train,
                epochs=50,
                batch_size=128,
                shuffle=True,
                validation_data=(x_test, x_test),
                 )

# we will check the prediction that about the data.
decoded_imgs = model.predict(x_test)

n = 10
plt.figure(figsize=(20, 4))

for i in range(1, 10):
    # display original
    ax = plt.subplot(2, n, i)
    plt.imshow(x_test[i].reshape(28, 28))
    plt.gray()
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)

    # display reconstruction
    ax = plt.subplot(2, n, i + 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()

#Deniosing 
#we will add now the noise in the image as we have take the image without noise.
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.)

n = 10
plt.figure(figsize=(20, 2))
for i in range(1, 10):
    ax = plt.subplot(1, n, i)
    plt.imshow(x_test_noisy[i].reshape(28, 28))
    plt.gray()
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
plt.show()

#Again build the CNN model

input_img = (28, 28, 1)

model2 = Sequential()

model2.add(Conv2D(16, (3, 3), activation='relu', padding='same', input_shape = input_img))
model2.add(MaxPooling2D((2, 2), padding='same'))

model2.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model2.add(MaxPooling2D((2, 2), padding='same'))

model2.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model2.add(MaxPooling2D((2, 2), padding='same'))

# at this point the representation is (4, 4, 8) i.e. 128-dimensional

model2.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model2.add(UpSampling2D((2, 2)))

model2.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model2.add(UpSampling2D((2, 2)))

model2.add(Conv2D(16, (3, 3), activation='relu'))
model2.add(UpSampling2D((2, 2)))

model2.add(Conv2D(1, (3, 3), activation='sigmoid', padding='same'))

model2.compile(optimizer='adam', 
              loss='binary_crossentropy', 
              metrics=['accuracy'])

model2.summary()

#fit the model
hist2 = model2.fit(x_train_noisy, x_train,
                epochs=50,
                batch_size=128,
                shuffle=True,
                validation_data=(x_test_noisy, x_test),
                 )
#final denoising will be done
decoded_imgs = model2.predict(x_test_noisy)

n = 10
plt.figure(figsize=(20, 4))

for i in range(1, 10):
    # display original
    ax = plt.subplot(2, n, i)
    plt.imshow(x_test_noisy[i].reshape(28, 28))
    plt.gray()
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)

    # display reconstruction
    ax = plt.subplot(2, n, i + 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()


#We need the following libraries for Denoising of image: 

from keras.datasets import mnist
import numpy as np
import matplotlib.pyplot as plt

from keras.layers import Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.models import Sequential
from keras import backend as K

#First we have to load the data (here we load data from MNIST Database)

(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))


#For denoising of the image we will use Autoencoder (, Autoencoders is a Reinforcement learning.) & Bulid the CNN Model.
#code
input_img = (28, 28, 1)

model = Sequential()

model.add(Conv2D(16, (3, 3), activation='relu', padding='same', input_shape = input_img))
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'))

# at this point the representation is (4, 4, 8) i.e. 128-dimensional

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'))
model.add(UpSampling2D((2, 2)))

model.add(Conv2D(1, (3, 3), activation='sigmoid', padding='same'))

model.compile(optimizer='adam', 
              loss='binary_crossentropy', 
              metrics=['accuracy'])

model.summary()

# we will show the machine how the data look like(fit the model ,“hist-is a variable”)

hist = model.fit(x_train, x_train,
                epochs=50,
                batch_size=128,
                shuffle=True,
                validation_data=(x_test, x_test),
                 )

# we will check the prediction that about the data.

decoded_imgs = model.predict(x_test)

n = 10
plt.figure(figsize=(20, 4))

for i in range(1, 10):
    # display original

    ax = plt.subplot(2, n, i)
    plt.imshow(x_test[i].reshape(28, 28))
    plt.gray()
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)

    # display reconstruction

    ax = plt.subplot(2, n, i + 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()

#Deniosing 
#we will add now the noise in the image as we have take the image without noise.

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.)

n = 10
plt.figure(figsize=(20, 2))
for i in range(1, 10):
    ax = plt.subplot(1, n, i)
    plt.imshow(x_test_noisy[i].reshape(28, 28))
    plt.gray()
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
plt.show()

#Again build the CNN model

input_img = (28, 28, 1)

model2 = Sequential()

model2.add(Conv2D(16, (3, 3), activation='relu', padding='same', input_shape = input_img))
model2.add(MaxPooling2D((2, 2), padding='same'))

model2.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model2.add(MaxPooling2D((2, 2), padding='same'))

model2.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model2.add(MaxPooling2D((2, 2), padding='same'))

# at this point the representation is (4, 4, 8) i.e. 128-dimensional

model2.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model2.add(UpSampling2D((2, 2)))

model2.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model2.add(UpSampling2D((2, 2)))

model2.add(Conv2D(16, (3, 3), activation='relu'))
model2.add(UpSampling2D((2, 2)))

model2.add(Conv2D(1, (3, 3), activation='sigmoid', padding='same'))

model2.compile(optimizer='adam', 
              loss='binary_crossentropy', 
              metrics=['accuracy'])

model2.summary()

#fit the model

hist2 = model2.fit(x_train_noisy, x_train,
                epochs=50,
                batch_size=128,
                shuffle=True,
                validation_data=(x_test_noisy, x_test),
                 )
#final denoising will be done

decoded_imgs = model2.predict(x_test_noisy)

n = 10
plt.figure(figsize=(20, 4))

for i in range(1, 10):
    # display original

    ax = plt.subplot(2, n, i)
    plt.imshow(x_test_noisy[i].reshape(28, 28))
    plt.gray()
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)

    # display reconstruction

    ax = plt.subplot(2, n, i + 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()


​
#We need the following libraries for Denoising of image: 

from keras.datasets import mnist
import numpy as np
import matplotlib.pyplot as plt

from keras.layers import Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.models import Sequential
from keras import backend as K

#First we have to load the data (here we load data from MNIST Database)

(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))


#For denoising of the image we will use Autoencoder (, Autoencoders is a Reinforcement learning.) & Build the CNN Model.
#code
input_img = (28, 28, 1)

model = Sequential()

model.add(Conv2D(16, (3, 3), activation='relu', padding='same', input_shape = input_img))
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'))

# at this point the representation is (4, 4, 8) i.e. 128-dimensional

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'))
model.add(UpSampling2D((2, 2)))

model.add(Conv2D(1, (3, 3), activation='sigmoid', padding='same'))

model.compile(optimizer='adam', 
              loss='binary_crossentropy', 
              metrics=['accuracy'])

model.summary()

# we will show the machine how the data look like(fit the model)

hist = model.fit(x_train, x_train,
                epochs=50,
                batch_size=128,
                shuffle=True,
                validation_data=(x_test, x_test),
                 )

# we will check the prediction that about the data.

decoded_imgs = model.predict(x_test)

n = 10
plt.figure(figsize=(20, 4))

for i in range(1, 10):
    # display original

    ax = plt.subplot(2, n, i)
    plt.imshow(x_test[i].reshape(28, 28))
    plt.gray()
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)

    # display reconstruction

    ax = plt.subplot(2, n, i + 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()

#Deniosing 
#we will add now the noise in the image as we have take the image without noise.

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.)

n = 10
plt.figure(figsize=(20, 2))
for i in range(1, 10):
    ax = plt.subplot(1, n, i)
    plt.imshow(x_test_noisy[i].reshape(28, 28))
    plt.gray()
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
plt.show()

#Again build the CNN model

input_img = (28, 28, 1)

model2 = Sequential()

model2.add(Conv2D(16, (3, 3), activation='relu', padding='same', input_shape = input_img))
model2.add(MaxPooling2D((2, 2), padding='same'))

model2.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model2.add(MaxPooling2D((2, 2), padding='same'))

model2.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model2.add(MaxPooling2D((2, 2), padding='same'))

# at this point the representation is (4, 4, 8) i.e. 128-dimensional

model2.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model2.add(UpSampling2D((2, 2)))

model2.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model2.add(UpSampling2D((2, 2)))

model2.add(Conv2D(16, (3, 3), activation='relu'))
model2.add(UpSampling2D((2, 2)))

model2.add(Conv2D(1, (3, 3), activation='sigmoid', padding='same'))

model2.compile(optimizer='adam', 
              loss='binary_crossentropy', 
              metrics=['accuracy'])

model2.summary()

#fit the model

hist2 = model2.fit(x_train_noisy, x_train,
                epochs=50,
                batch_size=128,
                shuffle=True,
                validation_data=(x_test_noisy, x_test),
                 )
#final denoising will be done

decoded_imgs = model2.predict(x_test_noisy)

n = 10
plt.figure(figsize=(20, 4))

for i in range(1, 10):
    # display original

    ax = plt.subplot(2, n, i)
    plt.imshow(x_test_noisy[i].reshape(28, 28))
    plt.gray()
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)

    # display reconstruction

    ax = plt.subplot(2, n, i + 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()


​​

Removing unwanted noising in order to restore the original image.
minify code