# Adding data augmentation right into the model import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.layers.experimental import preprocessing # Create a data augmentation stage with horizontal flipping, rotations, zooms data_augmentation = keras.Sequential([ preprocessing.RandomFlip("horizontal_and_vertical"), preprocessing.RandomRotation(0.3), preprocessing.RandomZoom(0.3), preprocessing.RandomHeight(0.3), preprocessing.RandomWidth(0.3), # preprocessing.Rescaling(1./255) # keep for ResNet50V2, remove for EfficientNetB0 ], name ="data_augmentation") # View a random image import matplotlib.pyplot as plt import matplotlib.image as mpimg import os import random target_class = random.choice(train_g.class_names) # choose a random class target_dir = "C:/Users/User/Desktop/computer vision/final_dataset/training/" + target_class # create the target directory random_image = random.choice(os.listdir(target_dir)) # choose a random image from target directory random_image_path = target_dir + "/" + random_image # create the choosen random image path img = mpimg.imread(random_image_path) # read in the chosen target image plt.imshow(img) # plot the target image plt.title(f"Original random image from class: {target_class}") plt.axis(False); # turn off the axes # Augment the image augmented_img = data_augmentation(tf.expand_dims(img, axis=0)) # data augmentation model requires shape (None, height, width, 3) plt.figure() plt.imshow(tf.squeeze(augmented_img)/255.) # requires normalization after augmentation plt.title(f"Augmented random image from class: {target_class}") plt.axis(False); # "C:/Users/User/Desktop/computer vision/final_dataset/training/"
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter