Skip to content

Instantly share code, notes, and snippets.

@Tob-iee
Created December 12, 2023 21:25
Show Gist options
  • Save Tob-iee/f861b6e2fe74beea3ffbc60a27a715d2 to your computer and use it in GitHub Desktop.
Save Tob-iee/f861b6e2fe74beea3ffbc60a27a715d2 to your computer and use it in GitHub Desktop.
Data Augmentation
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import os
from tensorflow.keras.preprocessing import image
import matplotlib.pyplot as plt
# Set the path to your dataset directory
dataset_directory = r"Path to your folder"
# Create an ImageDataGenerator with augmentation parameters
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'
)
# Specify the directory containing your images
image_directory = os.path.join(dataset_directory, 'images')
# Create the output directory if it doesn't exist
output_directory = os.path.join(dataset_directory, 'augmented_images')
if not os.path.exists(output_directory):
os.makedirs(output_directory)
# List all files in the input directory
image_files = [f for f in os.listdir(image_directory) if f.endswith(('.jpg', '.png'))]
# Loop through each image in the input directory
for image_file in image_files:
# Load the image
img_path = os.path.join(image_directory, image_file)
img = image.load_img(img_path, target_size=(150, 150))
x = image.img_to_array(img)
x = tf.expand_dims(x, axis=0)
# Generate augmented images and save to the output directory
i = 0
for batch in datagen.flow(x, batch_size=1, save_to_dir=output_directory, save_prefix='aug', save_format='jpeg'):
i += 1
if i > 4: # Generate 4 augmented images per original image
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment