Data Augmentation using tf. image
Introduction
Hey there! Data augmentation is a really cool technique to easily increase the diversity of your training set. This is done by applying several random but realistic transformations to the data such as image rotation. In this article, we will be discussing how to perform Data Augmentation using tf. image.
With that said, Let’s Get Started
Setup
Let’s start by importing some basic libraries that we’ll need:
import matplotlib.pyplot as pltimport numpy as npimport tensorflow as tfimport tensorflow_datasets as tfdsfrom tensorflow.keras import layers
Downloading the dataset
- I will be using the tf_flowers dataset for this demonstration. You can download the dataset using Tensorflow Datasets.
Use
pip install tensorflow datasets
to download it.
(train_ds, val_ds, test_ds), metadata = tfds.load('tf_flowers',split=['train[:80%]', 'train[80%:90%]', 'train[90%:]'],with_info=True,as_supervised=True,)
Fetch an image to work with
get_label_name = metadata.features['label'].int2strimage, label = next(iter(train_ds))_ = plt.imshow(image)_ = plt.title(get_label_name(label))
Let’s use the following function to visualize and compare the original and augmented images side-by-side.
def visualize(original, augmented):fig = plt.figure()plt.subplot(1,2,1)plt.title('Original image')plt.imshow(original)plt.subplot(1,2,2)plt.title('Augmented image')plt.imshow(augmented)
Now Let’s get into the Data Augmentation part
Flipping an Image
flipped = tf.image.flip_left_right(image)visualize(image, flipped)
Grayscale the image
grayscaled = tf.image.rgb_to_grayscale(image)visualize(image, tf.squeeze(grayscaled))_ = plt.colorbar()
Saturate the image
saturated = tf.image.adjust_saturation(image, 3)visualize(image, saturated)
Change image brightness
bright = tf.image.adjust_brightness(image, 0.4)visualize(image, bright)
Center crop the image
cropped = tf.image.central_crop(image, central_fraction=0.5)visualize(image,cropped)
Rotate the image
rotated = tf.image.rot90(image)visualize(image, rotated)
Conclusion
Hope you had fun working with Data Augmentation! Do check out my other articles where I cover topics such as deep learning and other trending technologies.
Thanks for stopping by! Happy Learning!
You can check out my Linkedin at https://www.linkedin.com/in/fabchris10/