File size: 4,028 Bytes
9877759
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
"""
image_augmentation.py

This script performs data augmentation on images using various transformations such as color jitter,
Gaussian blur, sharpness adjustment, horizontal flip, and vertical flip. 
It generates augmented images from an existing dataset and saves them to new folders.

"""

from PIL import Image
import os
from torchvision.utils import save_image
import torchvision.transforms as tvts
import random

# List of transformations for data augmentation
transforms=[tvts.ColorJitter(brightness=.5, hue=.3),
            tvts.GaussianBlur(kernel_size=(5, 9), sigma=(0.1, 5.)),
            tvts.RandomAdjustSharpness(sharpness_factor=2),
            tvts.RandomHorizontalFlip(p=0.5),
            tvts.RandomVerticalFlip(p=0.5)]

def select_random_imgs(img_list, count):
    """
    Selects a random subset of images from a list.

    Parameters:
        img_list (list): List of image filenames.
        count (int): Number of images to select.

    Returns:
        list: Randomly selected image filenames.
    """
    return random.sample(img_list, count)

def create_foldername(fname):
    """
    Creates a new folder name for augmented images.

    Parameters:
        fname (str): Original folder name.

    Returns:
        str: Augmented folder name.
    """
    names = fname.split("_")
    names.insert(2, "augment")
    return "_".join(names)

def save_original_imgs(source_fname, dest_fname, img_files):
    """
    Saves original images to the destination folder.

    Parameters:
        source_fname (str): Source folder name.
        dest_fname (str): Destination folder name.
        img_files (list): List of image filenames.
    """
    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)))

def open_PILimg(path):
    """
    Opens an image file using PIL.

    Parameters:
        path (str): File path to the image.

    Returns:
        PIL.Image.Image: PIL image object.
    """
    return Image.open(path).convert("RGB")
    
def augment_folder(root_fname, fname, augment_count=25):
    """
    Augments images in a folder and saves the augmented images to a new folder.

    Parameters:
        root_fname (str): Root folder containing the source images.
        fname (str): Name of the folder containing the source images.
        augment_count (int): Number of augmented images to generate for each original image.
    """
    onlyfiles = os.listdir(os.path.join(root_fname, fname))
    print(f'Befor augmentation, number of images: {len(onlyfiles)}')
    random_imgs = select_random_imgs(onlyfiles, len(onlyfiles))
    augment_fname = create_foldername(root_fname)
    if not os.path.exists(augment_fname):
        os.mkdir(augment_fname)
    
    save_fname = os.path.join(augment_fname, fname)

    if not os.path.exists(save_fname):
        os.mkdir(save_fname)

    save_original_imgs(source_fname=os.path.join(root_fname, fname), 
                       dest_fname=os.path.join(augment_fname, fname), 
                       img_files=onlyfiles)

    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(f"After augmentation, number of images: {len(os.listdir(save_fname))}")
    

if __name__ == "__main__":
    # Example usage
    root_folder = [["GNSS/Train"]]
    for root in root_folder:
        folders = [f for f in os.listdir(root) if os.path.isdir(os.path.join(root, f))]
        for folder in folders:
            augment_folder(root, folder)