0

i implemented a vanilla autoencoder in keras like this:

import numpy as np
from keras.preprocessing.image import *
from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.models import Model
from my_callback import Histories


input_img = Input(shape=(256, 256, 3))  # adapt this if using `channels_first` image data format

img = load_img('ss.png', target_size=(256,256))
#img.show()
img = np.array(img, dtype=np.float32) / 255 - 0.5
img=np.expand_dims(img,axis=0)


x = Conv2D(128, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(64, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling2D((2, 2), padding='same')(x)

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

x = Conv2D(32, (3, 3), activation='relu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(64, (3, 3), activation='relu',padding='same')(x)
x = UpSampling2D((2, 2))(x)
decoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)

autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')

h=Histories()

autoencoder.fit(img, img,
                epochs=300,
                batch_size=10,callbacks=[h])

Now

I had successfully made a GIF through saving each predicted image by autoencoder by keras.callbacks and then use imageio to make a gif with the help of this post programmatically-generate-video-or-animated-gif-in-python .The code was:

**my_callbacks.py**
import keras
import numpy as np
from matplotlib import pyplot as plt
from keras.preprocessing.image import load_img

class Histories(keras.callbacks.Callback):



    def on_epoch_end(self, epoch, logs=None):

        img = load_img('ss.png', target_size=(256, 256))
        img = np.array(img, dtype=np.float32) / 255 - 0.5
        img = np.expand_dims(img, axis=0)
        pixel = self.model.predict(img)
        pixel = pixel.reshape((256, 256, 3))
        #plt.imshow(pixel)
        #plt.show()
        print("saved images------------???????????????????????")
        plt.imsave('all_gif/pixelhash{0}.png'.format(epoch), pixel)
        return

And then the code to generate a gif of images from a folder.But sadly this code doesn't keep the order of images.Any solution?

import imageio
import os
filenames=os.listdir()
images = []
for filename in filenames:
     images.append(imageio.imread(filename))
imageio.mimsave('movie.gif', images)

But Is there any way to generate gif automatically without saving images in python like via matplotlib?

Amin Pial
  • 383
  • 6
  • 12

0 Answers0