Wednesday, October 18, 2017

Image generator of Keras: to make neural network with little data

Keras has image generator which works well when we don’t have enough amount of data. I’ll try this by simple example.

Overview


To make nice neural network model about images, we need much amount of data. In many cases, the shortage of data can be one of the big obstacles for goodness.
Keras has image generator and it can solves the problem.



Data


I’ll use rascal image from scipy.

import scipy
import matplotlib.pyplot as plt
face = scipy.misc.face()
plt.imshow(face)
plt.show()

enter image description here

Generate images


The image generator is easy to use. By giving the image to the generator, it randomly generates some types of images.
On the working directory:

mkdir temp

The images will be written out there.

from keras.preprocessing.image import ImageDataGenerator
datagen = ImageDataGenerator(
    rotation_range=20,
    width_shift_range=0.2,
    height_shift_range=0.2,
    horizontal_flip=True)


x = face.reshape((1,) + face.shape)
i = 0
for batch in datagen.flow(x, batch_size=1,
                          save_to_dir='temp', save_prefix='temp', save_format='jpeg'):
    i += 1
    if i > 20:
        break

The mosaic image composed of generated images is this.

enter image description here