-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaugment_data.py
More file actions
129 lines (106 loc) · 4.33 KB
/
Copy pathaugment_data.py
File metadata and controls
129 lines (106 loc) · 4.33 KB
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
import cv2
import numpy as np
import os
import shutil
from pathlib import Path
import random
def augment_image(image, bboxes, labels):
"""Apply various augmentations to image and adjust bounding boxes"""
h, w = image.shape[:2]
augmented_images = []
augmented_bboxes = []
augmented_labels = []
# Original image
augmented_images.append(image)
augmented_bboxes.append(bboxes)
augmented_labels.append(labels)
# Horizontal flip
flipped_img = cv2.flip(image, 1)
flipped_bboxes = []
for bbox in bboxes:
x, y, width, height = bbox
new_x = 1.0 - x - width # Flip x coordinate
flipped_bboxes.append([new_x, y, width, height])
augmented_images.append(flipped_img)
augmented_bboxes.append(flipped_bboxes)
augmented_labels.append(labels)
# Brightness adjustment
bright_img = cv2.convertScaleAbs(image, alpha=1.2, beta=30)
augmented_images.append(bright_img)
augmented_bboxes.append(bboxes)
augmented_labels.append(labels)
# Contrast adjustment
contrast_img = cv2.convertScaleAbs(image, alpha=1.3, beta=0)
augmented_images.append(contrast_img)
augmented_bboxes.append(bboxes)
augmented_labels.append(labels)
# Slight rotation
angle = random.uniform(-15, 15)
center = (w//2, h//2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated_img = cv2.warpAffine(image, M, (w, h))
# Note: Bounding box adjustment for rotation is complex, using original for simplicity
augmented_images.append(rotated_img)
augmented_bboxes.append(bboxes)
augmented_labels.append(labels)
return augmented_images, augmented_bboxes, augmented_labels
def parse_yolo_label(label_path):
"""Parse YOLO format label file"""
bboxes = []
labels = []
with open(label_path, 'r') as f:
for line in f:
parts = line.strip().split()
if len(parts) == 5:
class_id = int(parts[0])
x, y, w, h = map(float, parts[1:])
bboxes.append([x, y, w, h])
labels.append(class_id)
return bboxes, labels
def save_yolo_label(bboxes, labels, output_path):
"""Save bounding boxes in YOLO format"""
with open(output_path, 'w') as f:
for bbox, label in zip(bboxes, labels):
x, y, w, h = bbox
f.write(f"{label} {x} {y} {w} {h}\n")
def augment_dataset():
"""Augment the training dataset"""
base_dir = Path("data/train")
images_dir = base_dir / "images"
labels_dir = base_dir / "labels"
# Create augmented dataset directory
aug_dir = Path("data/train_augmented")
aug_images_dir = aug_dir / "images"
aug_labels_dir = aug_dir / "labels"
aug_images_dir.mkdir(parents=True, exist_ok=True)
aug_labels_dir.mkdir(parents=True, exist_ok=True)
image_files = list(images_dir.glob("*.png"))
print(f"Found {len(image_files)} images to augment")
total_augmented = 0
for img_path in image_files:
# Load image
image = cv2.imread(str(img_path))
if image is None:
continue
# Load corresponding label
label_path = labels_dir / f"{img_path.stem}.txt"
if not label_path.exists():
continue
bboxes, labels = parse_yolo_label(label_path)
# Apply augmentations
aug_images, aug_bboxes, aug_labels = augment_image(image, bboxes, labels)
# Save augmented images and labels
for i, (aug_img, aug_bbox, aug_label) in enumerate(zip(aug_images, aug_bboxes, aug_labels)):
# Save image
aug_img_path = aug_images_dir / f"{img_path.stem}_aug{i}.png"
cv2.imwrite(str(aug_img_path), aug_img)
# Save label
aug_label_path = aug_labels_dir / f"{img_path.stem}_aug{i}.txt"
save_yolo_label(aug_bbox, aug_label, aug_label_path)
total_augmented += 1
print(f"Augmentation complete! Generated {total_augmented} additional images")
return aug_dir
if __name__ == "__main__":
print("Starting dataset augmentation...")
augmented_dir = augment_dataset()
print(f"Augmented dataset saved to: {augmented_dir}")