Advertisement
UF6

Step I: Data Augmentation

UF6
Aug 5th, 2024
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | Source Code | 0 0
  1. from tensorflow.keras.preprocessing.image import ImageDataGenerator
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. import os
  5. from tensorflow.keras.preprocessing.image import load_img, img_to_array, array_to_img
  6.  
  7. # Load the single image
  8. img_path = 'path_to_your_image.jpg'
  9. img = load_img(img_path)
  10. x = img_to_array(img)
  11. x = x.reshape((1,) + x.shape)
  12.  
  13. # Define the augmentation configuration
  14. datagen = ImageDataGenerator(
  15.     rotation_range=40,
  16.     width_shift_range=0.2,
  17.     height_shift_range=0.2,
  18.     shear_range=0.2,
  19.     zoom_range=0.2,
  20.     horizontal_flip=True,
  21.     fill_mode='nearest')
  22.  
  23. # Generate batches of augmented images and save them
  24. save_to_dir = 'path_to_save_augmented_images'
  25. if not os.path.exists(save_to_dir):
  26.     os.makedirs(save_to_dir)
  27.  
  28. i = 0
  29. for batch in datagen.flow(x, batch_size=1, save_to_dir=save_to_dir, save_prefix='aug', save_format='jpeg'):
  30.     i += 1
  31.     if i > 20:
  32.         break  # Generate 20 augmented images
  33.  
  34. # Visualize the augmented images
  35. for file in os.listdir(save_to_dir):
  36.     img = load_img(os.path.join(save_to_dir, file))
  37.     plt.imshow(img)
  38.     plt.show()
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement