# 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()