Skip to content

Instantly share code, notes, and snippets.

@KevinPatel04
Last active July 11, 2020 10:21
Show Gist options
  • Save KevinPatel04/f0caca17ce1c4ec95046dbc76d85014f to your computer and use it in GitHub Desktop.
Save KevinPatel04/f0caca17ce1c4ec95046dbc76d85014f to your computer and use it in GitHub Desktop.
Data Augmentation
# find the mean of the pixels
x.mean()
# define and initialize ImageDataGenerator class
generator = tf.keras.preprocessing.image.ImageDataGenerator(
rescale = 1.,
channel_shift_range = 100,
width_shift_range = [-100, -50, 0, 50, 100],
height_shift_range = [-50, 0, 50],
horizontal_flip = True,
vertical_flip = True
)
# find the mean of the original image
np.array(Image.open(image_path)).mean()
# define and initialize ImageDataGenerator class
generator = tf.keras.preprocessing.image.ImageDataGenerator(
brightness_range = (0.5,2.) # brightness_range: tuple or list or two Float values are accpeted
)
# define and initialize ImageDataGenerator class
generator = tf.keras.preprocessing.image.ImageDataGenerator(
channel_shift_range = 100 # channel_shift_range: Float value is accepted
)
•
├── images
│   └── dog
│       ├── dog.jpg
│       ├── dog1.jpg
│       └── dog2.jpg
└── data-augmentation.ipynb
# load the sample dataset using keras
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
# define and initialize ImageDataGenerator class
generator = tf.keras.preprocessing.image.ImageDataGenerator(
featurewise_center = True, # featurewise_center: boolean value True for setting the input mean to 0
featurewise_std_normalization = True, # featurewise_std_normalization: boolean value divide inputs by std of the dataset feature-wise
)
generator.fit(x_train)
# using flow() function apply the generator to generate batch of augmented data
x, y = next(generator.flow(x_train, y_train, batch_size = 1))
# print the mean of the original data
print(x_train.mean())
# print the mean and standard deviation for the of the augmentated dataset
print(x.mean(), x.std(), y)
# define and initialize ImageDataGenerator class
generator = tf.keras.preprocessing.image.ImageDataGenerator(
horizontal_flip = True, # horizontal_flip: boolean value True for enabling horizontal flip
vertical_flip = True, # horizontal_flip: boolean value True for enabling horizontal flip
)
# initialize the base directory path that contains images
DIR_PATH = 'images'
# initialize the Batch Size
BATCH_SIZE = 1
# using flow_from_directory() function apply the generator to generate batch of augmented data
x, y = next(generator.flow_from_directory(directory = DIR_PATH, batch_size = BATCH_SIZE))
# show the augmented result
plt.imshow(x[0].astype('uint8'));
# define and initialize ImageDataGenerator class
generator = tf.keras.preprocessing.image.ImageDataGenerator(
width_shift_range = [-100, -50, 0, 50, 100], # width_shift_range: tuple, list, Int or Float value are accepted
height_shift_range = [-50, 0, 50] # height_shift_range: tuple, list, Int or Float value are accepted
)
tf.keras.preprocessing.image.ImageDataGenerator(
    featurewise_center=False,
    samplewise_center=False,
    featurewise_std_normalization=False,
    samplewise_std_normalization=False,
    zca_whitening=False,
    zca_epsilon=1e-06,
    rotation_range=0,
    width_shift_range=0.0,
    height_shift_range=0.0,
    brightness_range=None,
    shear_range=0.0,
    zoom_range=0.0,
    channel_shift_range=0.0,
    fill_mode="nearest",
    cval=0.0,
    horizontal_flip=False,
    vertical_flip=False,
    rescale=None,
    preprocessing_function=None,
    data_format=None,
    validation_split=0.0,
    dtype=None,
)
# import libraries
%matplotlib inline
import os
import numpy as np
import tensorflow as tf
from PIL import Image
from matplotlib import pyplot as plt
# define and initialize ImageDataGenerator class
generator = tf.keras.preprocessing.image.ImageDataGenerator(
# preprocessing_function: function that will be applied on each input. The function will run after
# the image is resized and augmented. The function should take one argument: one image (Numpy tensor with rank 3),
# and should output a Numpy tensor with the same shape.
preprocessing_function = tf.keras.applications.mobilenet_v2.preprocess_input
)
# initialize the path
image_path = 'images/dog/dog.jpg'
# read image file using matplotlib's imread() function
image = plt.imread(image_path)
# using matplotlib's imshow() function display the image
plt.imshow(image);
# define and initialize ImageDataGenerator class
generator = tf.keras.preprocessing.image.ImageDataGenerator(
rescale = 1. # rescale: define the rescaling factor
)
# define and initialize ImageDataGenerator class
generator = tf.keras.preprocessing.image.ImageDataGenerator(
rotation_range = 40 # rotation_range: Int degree range for random rotations
)
# load the sample dataset using keras
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
# define and initialize ImageDataGenerator class
generator = tf.keras.preprocessing.image.ImageDataGenerator(
samplewise_center = True,
samplewise_std_normalization = True
)
# using flow() function apply the generator to generate batch of augmented data
x, y = next(generator.flow(x_train, y_train, batch_size=1))
# print the mean of the original data
print(x_train.mean())
# print the mean and standard deviation for the of the augmentated dataset
print(x.mean(), x.std(), y)
# define and initialize ImageDataGenerator class
generator = tf.keras.preprocessing.image.ImageDataGenerator(
shear_range = 40 # shear_range: Float value that indicates counter-clockwise shear angle in degrees
)
generator = tf.keras.preprocessing.image.ImageDataGenerator(
horizontal_flip = True,
rotation_range = 20,
preprocessing_function = tf.keras.applications.mobilenet_v2.preprocess_input
)
model = tf.keras.models.Sequential([
tf.keras.applications.mobilenet_v2.MobileNetV2(
include_top = False,
input_shape = (32,32,3),
pooling = 'avg'
),
tf.keras.layers.Dense(10,activation = 'softmax')
])
model.compile(
loss = 'sparse_categorical_crossentropy',
optimizer = 'adam',
metrics = ['accuracy']
)
_ = model.fit(
generator.flow(x_train,y_train,batch_size = 32),
epochs = 1,
steps_per_epoch = 10,
)
# define and initialize ImageDataGenerator class
generator = tf.keras.preprocessing.image.ImageDataGenerator(
zoom_range = 0.5 # zoom_range: list or Int or Float value are accepted
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment