|
- {
- "cells": [
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "import os\n",
- "import numpy as np\n",
- "from tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img, array_to_img\n",
- "\n",
- "# Define the source and destination directories\n",
- "source_directory = 'path_to_your_images'\n",
- "augmented_directory = 'path_to_save_augmented_images'\n",
- "\n",
- "# Create the destination directory if it does not exist\n",
- "if not os.path.exists(augmented_directory):\n",
- " os.makedirs(augmented_directory)\n",
- "\n",
- "# Initialize the ImageDataGenerator with augmentation parameters\n",
- "datagen = ImageDataGenerator(\n",
- " rotation_range=40,\n",
- " width_shift_range=0.2,\n",
- " height_shift_range=0.2,\n",
- " shear_range=0.2,\n",
- " zoom_range=0.2,\n",
- " horizontal_flip=True,\n",
- " fill_mode='nearest'\n",
- ")\n",
- "\n",
- "# Function to augment and save images\n",
- "def augment_images(image_path, save_to_dir, prefix='aug', num_augmented_images=5):\n",
- " img = load_img(image_path) # Load image\n",
- " x = img_to_array(img) # Convert image to array\n",
- " x = np.expand_dims(x, axis=0) # Expand dimensions to match the input shape required by the generator\n",
- "\n",
- " # Generate augmented images and save them\n",
- " i = 0\n",
- " for batch in datagen.flow(x, batch_size=1, save_to_dir=save_to_dir, save_prefix=prefix, save_format='jpeg'):\n",
- " i += 1\n",
- " if i >= num_augmented_images:\n",
- " break\n",
- "\n",
- "# Loop over images in the source directory\n",
- "for filename in os.listdir(source_directory):\n",
- " if filename.endswith(\".jpg\") or filename.endswith(\".png\"):\n",
- " image_path = os.path.join(source_directory, filename)\n",
- " augment_images(image_path, augmented_directory)\n",
- "\n",
- "print(\"Data augmentation completed!\")\n"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
- }
|