Skip to content

Instantly share code, notes, and snippets.

@algonacci
Created April 24, 2023 14:01
Show Gist options
  • Save algonacci/a319b00e19ab8bb2da92dd5a394c006c to your computer and use it in GitHub Desktop.
Save algonacci/a319b00e19ab8bb2da92dd5a394c006c to your computer and use it in GitHub Desktop.
A simple script to augment image dataset
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "d4f95b5c",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"from PIL import Image"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "f6c5e6e8",
"metadata": {},
"outputs": [],
"source": [
"FOLDER_PATH = 'C:/Users/Socio/Desktop/Bangkit_Dataset/Plant_Diseases_Augmented/train/Rice_Leaf_Smut/'\n",
"OUTPUT_PATH = 'C:/Users/Socio/Desktop/Bangkit_Dataset/Plant_Diseases_Augmented/train/Rice_Leaf_Smut/'"
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "226a8ca7",
"metadata": {},
"outputs": [],
"source": [
"for i, filename in enumerate(os.listdir(FOLDER_PATH)):\n",
" # Open the image\n",
" img = Image.open(os.path.join(FOLDER_PATH, filename))\n",
" \n",
" if img.mode == 'RGBA':\n",
" img = img.convert('RGB')\n",
" \n",
" # Flip the image horizontally\n",
" flipped_img = img.transpose(Image.FLIP_LEFT_RIGHT)\n",
" \n",
" # Save the flipped image to the output directory\n",
" flipped_img.save(os.path.join(OUTPUT_PATH, f'{i}_flipped.jpg'))\n",
" \n",
"# # Flip the image vertically\n",
"# flipped_img = img.transpose(Image.FLIP_TOP_BOTTOM)\n",
" \n",
"# # Save the flipped image to the output directory\n",
"# flipped_img.save(os.path.join(OUTPUT_PATH, f'{i}_flipped_vertically.jpg'))"
]
},
{
"cell_type": "code",
"execution_count": 25,
"id": "69f61825",
"metadata": {},
"outputs": [],
"source": [
"for i, filename in enumerate(os.listdir(FOLDER_PATH)):\n",
" os.rename(os.path.join(FOLDER_PATH, filename), os.path.join(FOLDER_PATH, f'{i}.jpg'))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.0"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment