Skip to content

Instantly share code, notes, and snippets.

@TanjimReza
Created July 21, 2023 18:17
Show Gist options
  • Save TanjimReza/d852ad572bbc8f69f954e49f4e807889 to your computer and use it in GitHub Desktop.
Save TanjimReza/d852ad572bbc8f69f954e49f4e807889 to your computer and use it in GitHub Desktop.
Rename all the images of subdirectory images according to subdirectory name and save it in output folder with 30random shuffle
# Get All Folders and SubFolders, Get all the images in the folder and rename them according to the folder name
import os
import random
import time
start_time = time.time()
SELECT_LIMIT = 30
current_dir = os.getcwd()
print(current_dir)
#! Get all the folder names
print(f"{'-'*50}")
print("Getting all the folder names...")
folder_names = os.listdir(current_dir)[:-1]
print(folder_names)
print(f"{'-'*50}")
#! Iterate through all the folders
print("Iterating through all the folders...")
for folder in folder_names:
print(f"Current Folder: {folder}")
#! Get all the images in the folder
print(f"Getting all the images in the folder: {folder}")
# for image in os.listdir(folder):
# print(f"Current Image: {image}")
image_names_list = os.listdir(folder)
# print(f"Images in {folder}: {image_names_list}")
#! Shuffle the image names list
print(f"Shuffling the images...")
random.shuffle(image_names_list)
# print(f"Shuffled Images in {folder}: {image_names_list}")
selected_images = image_names_list[:SELECT_LIMIT]
print(f"Selected Images in {folder}: {selected_images}")
#! Rename the images
print(f"Renaming the images...")
image_number = 1
for image_name in selected_images:
print("Current Image: ", image_name)
#! Get the extension of the image
image_extension = image_name.split(".")[-1]
print("Image Extension: ", image_extension)
#! Rename the image
new_image_name = f"{folder}_{image_number}.{image_extension}"
print("New Image Name: ", new_image_name)
#! Rename the image and save to output folder
#! Check if the output folder exists
if not os.path.exists("output"):
os.mkdir("output")
os.rename(f"{folder}/{image_name}", f"output/{new_image_name}")
image_number += 1
print(f"{'-'*50}")
print(f"{'-'*50}")
end_time = time.time()
print(f"Time Taken: {end_time - start_time} seconds")
print(f"{'-'*50}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment