You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

63 line
2.1 KiB

  1. {
  2. "cells": [
  3. {
  4. "cell_type": "code",
  5. "execution_count": null,
  6. "metadata": {},
  7. "outputs": [],
  8. "source": [
  9. "import os\n",
  10. "import numpy as np\n",
  11. "from tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img, array_to_img\n",
  12. "\n",
  13. "# Define the source and destination directories\n",
  14. "source_directory = 'path_to_your_images'\n",
  15. "augmented_directory = 'path_to_save_augmented_images'\n",
  16. "\n",
  17. "# Create the destination directory if it does not exist\n",
  18. "if not os.path.exists(augmented_directory):\n",
  19. " os.makedirs(augmented_directory)\n",
  20. "\n",
  21. "# Initialize the ImageDataGenerator with augmentation parameters\n",
  22. "datagen = ImageDataGenerator(\n",
  23. " rotation_range=40,\n",
  24. " width_shift_range=0.2,\n",
  25. " height_shift_range=0.2,\n",
  26. " shear_range=0.2,\n",
  27. " zoom_range=0.2,\n",
  28. " horizontal_flip=True,\n",
  29. " fill_mode='nearest'\n",
  30. ")\n",
  31. "\n",
  32. "# Function to augment and save images\n",
  33. "def augment_images(image_path, save_to_dir, prefix='aug', num_augmented_images=5):\n",
  34. " img = load_img(image_path) # Load image\n",
  35. " x = img_to_array(img) # Convert image to array\n",
  36. " x = np.expand_dims(x, axis=0) # Expand dimensions to match the input shape required by the generator\n",
  37. "\n",
  38. " # Generate augmented images and save them\n",
  39. " i = 0\n",
  40. " for batch in datagen.flow(x, batch_size=1, save_to_dir=save_to_dir, save_prefix=prefix, save_format='jpeg'):\n",
  41. " i += 1\n",
  42. " if i >= num_augmented_images:\n",
  43. " break\n",
  44. "\n",
  45. "# Loop over images in the source directory\n",
  46. "for filename in os.listdir(source_directory):\n",
  47. " if filename.endswith(\".jpg\") or filename.endswith(\".png\"):\n",
  48. " image_path = os.path.join(source_directory, filename)\n",
  49. " augment_images(image_path, augmented_directory)\n",
  50. "\n",
  51. "print(\"Data augmentation completed!\")\n"
  52. ]
  53. }
  54. ],
  55. "metadata": {
  56. "language_info": {
  57. "name": "python"
  58. }
  59. },
  60. "nbformat": 4,
  61. "nbformat_minor": 2
  62. }