FelixOtt's picture
Upload folder using huggingface_hub
9877759 verified
Raw History Blame Contribute Delete
4.51 kB
from PIL import Image
import os
import numpy as np
import torch
from torchvision.utils import save_image
import torchvision.transforms as tvts
import random
from os import listdir
from os.path import isfile, join
import shutil
# Define a list of augmentation transformations to be applied to images
transforms = [
tvts.ColorJitter(brightness=.5, hue=.3), # Adjust brightness and hue
tvts.GaussianBlur(kernel_size=(5, 9), sigma=(0.1, 5.)), # Apply Gaussian blur with random parameters
tvts.RandomAdjustSharpness(sharpness_factor=2), # Adjust image sharpness
tvts.RandomRotation(degrees=(0, 180)), # Rotate images randomly between 0 and 180 degrees
tvts.RandomHorizontalFlip(p=0.5), # Randomly flip images horizontally
tvts.RandomVerticalFlip(p=0.5) # Randomly flip images vertically
]
# Select a specified number of random images from a list
def select_random_imgs(img_list, count):
return random.sample(img_list, count)
# Create a new folder name by adding "augment" to the original name
def create_foldername(fname):
names = fname.split("_")
names.insert(2, "augment")
return "_".join(names)
# Save original images to a new destination folder without applying transformations
def save_original_imgs(source_fname, dest_fname, img_files):
for img in img_files:
img_name = img.split(".")[0]
img = open_PILimg(path=os.path.join(source_fname, img))
save_image(tvts.ToTensor()(img), os.path.join(dest_fname, "{}.jpg".format(img_name)))
# Select a specified number of random files and copy them to the destination folder
def select_random_files(count, source_fname, dest_fname):
files = os.listdir(source_fname)
files = select_random_imgs(files, count=count)
# Iterate through the files and copy them to the destination folder
for file in files:
source_path = os.path.join(source_fname, file)
destination_path = os.path.join(dest_fname, file)
shutil.copy(source_path, destination_path)
print(f"Copied {file} to {dest_fname}")
# Open an image file using PIL and convert it to RGB format
def open_PILimg(path):
return Image.open(path).convert("RGB")
# Save a PIL image to the specified path
def save_PILimg(path, img):
save_image(tvts.ToTensor()(img), "{}.jpg".format(path))
# Function to augment images in a specific folder
def augment_folder(root_fname, fname, augment_count=25):
# Get the list of all images in the folder
onlyfiles = os.listdir(os.path.join(root_fname, fname))
print("Before augmentation, number of images in {} is {}".format(root_fname, len(onlyfiles)))
# Randomly select images to be augmented
random_imgs = select_random_imgs(onlyfiles, len(onlyfiles))
augment_fname = create_foldername(root_fname)
# Create folder for augmented images if it does not exist
if not os.path.exists(augment_fname):
os.mkdir(augment_fname)
# Create a sub-folder for the specific set of images
save_fname = os.path.join(augment_fname, fname)
if not os.path.exists(save_fname):
os.mkdir(save_fname)
# Save the original images in the new folder
save_original_imgs(source_fname=os.path.join(root_fname, fname),
dest_fname=os.path.join(augment_fname, fname),
img_files=onlyfiles)
# Apply transformations and save augmented images
for img in random_imgs:
img_name = img.split(".")[0]
img = open_PILimg(path=os.path.join(root_fname, fname, img))
for transform in transforms:
transname = transform.__class__.__name__
transformed_imgs = [transform(img) for _ in range(augment_count)]
for i, trans_img in enumerate(transformed_imgs):
save_image(tvts.ToTensor()(trans_img), os.path.join(save_fname, "trans_img_{}_{}_{}.jpg".format(img_name, transname, i)))
print("After augmentation, number of images in {} is {}".format(save_fname, len(os.listdir(save_fname))))
# Main block to iterate over root folders ("Train" and "Test") and apply augmentations
if __name__ == "__main__":
root_folder = [["Train"], ["Test"]]
for root in root_folder:
# List all subfolders within the root directory
folders = [f for f in os.listdir(root) if os.path.isdir(os.path.join(root, f))]
# Apply augmentation to each subfolder
for folder in folders:
augment_folder(root, folder)