Skip to content

Instantly share code, notes, and snippets.

@Wapiti08
Last active June 14, 2020 07:13
Show Gist options
  • Save Wapiti08/d6a242565c679e55af20b1b83463b9dd to your computer and use it in GitHub Desktop.
Save Wapiti08/d6a242565c679e55af20b1b83463b9dd to your computer and use it in GitHub Desktop.
Easy way to do pre-processing for Image Process in NN

The way to do pre-processing

from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
    train_dir,
    batch_size=20,
    target_size=(150, 150)
    class_mode = 'binary'
  )

for data_batch, labels_batch in train_generator:
  print('data batch shape', data_batch)
  print('labels batch shape', labels_batch.shape)

history = model.fit_generator(
  train_generator,
  steps_per_epoch=100,
  epochs=30,
  validation_data = validation_generator,
  validation_steps = 50)

model.save('xxx.h5')

The way to augement the images with limited size of images samples

datagen = ImageDataGenerator(
      rotation_range=40,
      width_shift_range=0.2,
      height_shift_range=0.2,
      shear_range=0.2,
      zoom_range=0.2,
      horizontal_flip=True,
      fill_mode='nearest')
      
# to call the instance
i=0
for batch in datagen.flow(x, batch_size=1):
    plt.figure(i)
    imgplot = plt.imshow(image.array_to_img(batch[0]))
    i += 1
    if i % 4 == 0:
        break

plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment