File size: 10,314 Bytes
5ed72c3
bb93c50
404e2b5
 
 
bb93c50
404e2b5
 
 
 
 
 
 
bb93c50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# Copyright 2025 Robotics Group of the University of León (ULE)

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import random
from pathlib import Path
import numpy as np
from PIL import Image, ImageEnhance, ImageOps, ImageFilter
from tqdm import tqdm


def load_image(image_path):
    """Load an image from the file system.
    
    Args:
        image_path: Path to the image file.
        
    Returns:
        Loaded PIL Image object.
    """
    return Image.open(image_path)


def save_image(image, output_path):
    """Save the image to the specified path.
    
    Args:
        image: PIL Image object to save.
        output_path: Destination path for the image.
    """
    image.save(output_path)


def flip_horizontal(image):
    """Flip the image horizontally.
    
    Args:
        image: Input PIL Image.
        
    Returns:
        Horizontally flipped PIL Image.
    """
    return ImageOps.mirror(image)


def rotate(image, angle):
    """Rotate the image by the specified angle.
    
    Args:
        image: Input PIL Image.
        angle: Rotation angle in degrees (positive = counter-clockwise).
        
    Returns:
        Rotated PIL Image.
    """
    return image.rotate(angle, expand=False)


def adjust_brightness(image, factor):
    """Adjust the brightness of the image.
    
    Args:
        image: Input PIL Image.
        factor: Brightness adjustment factor (1.0 = original, <1.0 darker, >1.0 brighter).
        
    Returns:
        Brightness-adjusted PIL Image.
    """
    enhancer = ImageEnhance.Brightness(image)
    return enhancer.enhance(factor)


def adjust_contrast(image, factor):
    """Adjust the contrast of the image.
    
    Args:
        image: Input PIL Image.
        factor: Contrast adjustment factor (1.0 = original, <1.0 less contrast, >1.0 more contrast).
        
    Returns:
        Contrast-adjusted PIL Image.
    """
    enhancer = ImageEnhance.Contrast(image)
    return enhancer.enhance(factor)


def adjust_saturation(image, factor):
    """Adjust the saturation of the image.
    
    Args:
        image: Input PIL Image.
        factor: Saturation adjustment factor (1.0 = original, 0.0 = grayscale, >1.0 more saturated).
        
    Returns:
        Saturation-adjusted PIL Image.
    """
    enhancer = ImageEnhance.Color(image)
    return enhancer.enhance(factor)


def add_noise(image, intensity=0.05):
    """Add random noise to the image.
    
    Args:
        image: Input PIL Image.
        intensity: Noise intensity factor (0.0-1.0). Defaults to 0.05.
        
    Returns:
        PIL Image with added noise.
    """
    img_array = np.array(image).copy()
    if len(img_array.shape) == 3:
        h, w, c = img_array.shape
        noise = np.random.randint(-int(intensity * 255), int(intensity * 255), (h, w, c))
        img_array = np.clip(img_array + noise, 0, 255).astype(np.uint8)
    else:
        h, w = img_array.shape
        noise = np.random.randint(-int(intensity * 255), int(intensity * 255), (h, w))
        img_array = np.clip(img_array + noise, 0, 255).astype(np.uint8)
    return Image.fromarray(img_array)


def apply_blur(image, radius=2):
    """Apply Gaussian blur to the image.
    
    Args:
        image: Input PIL Image.
        radius: Blur radius in pixels. Defaults to 2.
        
    Returns:
        Blurred PIL Image.
    """
    return image.filter(ImageFilter.GaussianBlur(radius=radius))

def transform_yolo_label(label_line, technique_name):
    """Transform YOLO format label coordinates based on the augmentation technique.
    
    Args:
        label_line: A line from a YOLO label file (class_id center_x center_y width height).
        technique_name: The augmentation technique applied.
        
    Returns:
        Transformed label line in YOLO format.
    """
    parts = label_line.strip().split()
    if len(parts) < 5:
        return label_line
    
    class_id = parts[0]
    x_center = float(parts[1])
    y_center = float(parts[2])
    width = float(parts[3])
    height = float(parts[4])
    
    if technique_name == "flip_horizontal":
        x_center = 1.0 - x_center
    
    return f"{class_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}"


def process_yolo_label(original_label_path, new_label_path, technique_name):
    """Process a YOLO format label file, applying transformations to the coordinates.
    
    Args:
        original_label_path: Path to the original label file.
        new_label_path: Path for the new transformed label file.
        technique_name: Name of the augmentation technique applied.
        
    Returns:
        True if processing was successful, False otherwise.
    """
    if not original_label_path.exists():
        return False
    
    with open(original_label_path, "r") as infile:
        lines = infile.readlines()
    
    new_lines = []
    for line in lines:
        if line.strip():
            if technique_name in ["adjust_brightness", "adjust_contrast", 
                                  "adjust_saturation", "add_noise", "apply_blur"]:
                new_lines.append(line.strip())
            else:
                transformed_line = transform_yolo_label(line, technique_name)
                new_lines.append(transformed_line)
    
    os.makedirs(new_label_path.parent, exist_ok=True)
    
    with open(new_label_path, "w") as outfile:
        outfile.write("\n".join(new_lines))
    
    return True

def augment_yolo_dataset(base_dir, augmentations_per_image=3):
    """Apply data augmentation to images in a YOLO dataset.
    
    For each image in the dataset, this function applies a specified number of random
    augmentation techniques and transforms the corresponding YOLO label files to maintain
    annotation accuracy.
    
    Args:
        base_dir: Base directory of the YOLO dataset (should contain images/ and labels/).
        augmentations_per_image: Number of random augmentations per image. Defaults to 3.
    """
    images_dir = os.path.join(base_dir, "images")
    labels_dir = os.path.join(base_dir, "labels")
    
    if not os.path.exists(images_dir):
        print(f"Error: Images directory not found at {images_dir}")
        return
    
    if not os.path.exists(labels_dir):
        print(f"Error: Labels directory not found at {labels_dir}")
        return
    
    image_extensions = [".jpg", ".jpeg", ".png", ".bmp"]
    image_files = []
    
    for ext in image_extensions:
        image_files.extend(list(Path(images_dir).glob(f"*{ext}")))
    
    print(f"Found {len(image_files)} images in {images_dir}")
    
    augmentation_techniques = [
        (flip_horizontal, {}, "flip_horizontal"),
        (rotate, {"angle": lambda: random.randint(-15, 15)}, "rotate"),
        (adjust_brightness, {"factor": lambda: random.uniform(0.8, 1.2)}, "adjust_brightness"),
        (adjust_contrast, {"factor": lambda: random.uniform(0.8, 1.2)}, "adjust_contrast"),
        (adjust_saturation, {"factor": lambda: random.uniform(0.8, 1.2)}, "adjust_saturation"),
        (add_noise, {"intensity": lambda: random.uniform(0.01, 0.05)}, "add_noise"),
        (apply_blur, {"radius": lambda: random.uniform(0.5, 1.5)}, "apply_blur")
    ]
    
    total_augmented = 0
    labels_processed = 0
    
    for img_path in tqdm(image_files, desc="Augmenting images"):
        try:
            original_image = load_image(img_path)
            
            rel_path = img_path.relative_to(images_dir)
            label_path = Path(labels_dir) / rel_path.with_suffix(".txt")
            
            if not label_path.exists():
                continue
            
            for i in range(augmentations_per_image):
                technique, params, technique_name = random.choice(augmentation_techniques)
                
                resolved_params = {k: v() if callable(v) else v for k, v in params.items()}
                
                augmented_image = original_image.copy()
                augmented_image = technique(augmented_image, **resolved_params)
                
                filename = img_path.stem
                extension = img_path.suffix
                augmented_filename = f"{filename}_aug_{technique_name}_{i + 1}{extension}"
                augmented_path = img_path.parent / augmented_filename
                save_image(augmented_image, augmented_path)
                
                augmented_label_path = label_path.parent / f"{filename}_aug_{technique_name}_{i + 1}.txt"
                if process_yolo_label(label_path, augmented_label_path, technique_name):
                    labels_processed += 1
                
                total_augmented += 1
                
        except Exception as e:
            tqdm.write(f"Error processing {img_path.name}: {str(e)}")
            continue
    
    print(f"Created {total_augmented} augmented images")
    print(f"Processed {labels_processed} YOLO label files")
    
    train_txt_path = os.path.join(base_dir, "train.txt")
    if os.path.exists(train_txt_path):
        all_images = []
        for ext in image_extensions:
            all_images.extend([str(p.relative_to(base_dir)) for p in Path(images_dir).glob(f"*{ext}")])
        
        with open(train_txt_path, "w") as f:
            f.write("\n".join(all_images))
        print(f"Updated {train_txt_path} with {len(all_images)} image paths")

def main():
    """Main function to execute dataset augmentation.
    
    Configures the base directory and number of augmentations, then runs the
    augmentation pipeline on the YOLO dataset.
    """
    train_dir = "/home/pcrn/datainbrief/beet_augmented/train"
    augmentations_per_image = 3
    
    print(f"Starting augmentation on YOLO dataset in {train_dir}")
    augment_yolo_dataset(train_dir, augmentations_per_image)


if __name__ == "__main__":
    main()