-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_augmentations.py
195 lines (167 loc) · 6.01 KB
/
data_augmentations.py
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
# pip install pascal-voc-writer
# !pip install --upgrade albumentations
# ######################################################
# VISUALIZATION OF CREATED AUGMENTED IMAGES AND BOUNDING BOXES
# #######################################################
import random
import cv2
from matplotlib import pyplot as plt
import matplotlib.patches as patches
import numpy as np
import albumentations as A
##########################################
# DEFINING PATHS
images_path = '/Users/student/Work/IIQ/og_fire/images'
annotations_path = '/Users/student/Work/IIQ/og_fire/annotations'
new_annotations_path = '/Users/student/Work/IIQ/og_fire/new_anns'
new_images_path = '//Users/student/Work/IIQ/og_fire/new_images'
############################################
def visualize(image):
plt.figure(figsize=(10, 10))
plt.axis('off')
plt.imshow(image)
plt.show()
def plot_example(image,bboxes):
fig = plt.figure(figsize=(15,15))
if bboxes is not None:
for bbox in bboxes:
x_min = int(bbox[0])
y_min = int(bbox[1])
x_max = int(bbox[2])
y_max = int(bbox[3])
cv2.rectangle(image, (x_min, y_min), (x_max, y_max), (255, 0, 0), 5)
plt.imshow(image)
plt.show()
def plotExamples(images,all_bboxes):
i = 0
for bboxes in all_bboxes:
plot_example(images[i],bboxes)
i+=1
import albumentations as A
from imgaug.augmentables.bbs import BoundingBox, BoundingBoxesOnImage
# from bbaug import policies
import cv2
import os
from pascal_voc_writer import Writer
from xml.dom import minidom
import xml.etree.ElementTree as ET
import imgaug as ia
import imgaug.augmenters as iaa
import math
import random
import copy
import glob
from PIL import Image
import numpy as np
random.seed(7)
def readImage(filename):
# Reading Image using PIL
# images_path = '/Users/student/Work/IIQ/Augmentations_fire_kurle/Fire_Detection-2/Images'
im_path = images_path + '/'+ filename
os.chdir(images_path)
image = Image.open(filename)
image = np.array(image)
return image
def getCoordinates(filename):
# annotations_path = '/Users/student/Work/IIQ/Augmentations_fire_kurle/Fire_Detection-2/XML'
os.chdir(annotations_path)
my_tree = ET.parse(filename)
my_root = my_tree.getroot()
# getting the coordinates
allbb = []
for obj in my_root.findall('object'):
classid = str(obj.find('name').text)
bndbox = obj.find('bndbox')
xmin =0
ymin =0
xmax =0
ymax =0
xmin = int(bndbox.find('xmin').text)
xmax = int(bndbox.find('xmax').text)
ymin = int(bndbox.find('ymin').text)
ymax = int(bndbox.find('ymax').text)
b = [xmin, ymin, xmax, ymax, classid]
allbb.append(b)
# print(allbb)
return allbb
# modidy the XML with new coordinates and store in a new place
def modifyXML_andSave(filename,new_image_name, bboxes):
# annotations_path = '/Users/student/Work/IIQ/Augmentations_fire_kurle/Fire_Detection-2/XML'
# new_annotations_path = '/Users/student/Work/IIQ/Augmentations_fire_kurle/new_anns'
os.chdir(annotations_path)
my_tree = ET.parse(filename)
my_root = my_tree.getroot()
my_root.find('filename').text = new_image_name
for bbox in bboxes:
name = bbox[-1]
# print(name)
for obj in my_root.findall('object'):
obj_name = obj.find('name')
if (obj_name.text == name):
# print("right object found")
bndbox = obj.find('bndbox')
bndbox.find('xmin').text = str(bbox[0])
bndbox.find('xmax').text = str(bbox[1])
bndbox.find('ymin').text = str(bbox[2])
bndbox.find('ymax').text = str(bbox[3])
# bndbox.find('xmin').text = str("{:.2f}".format(bbox[0]))
# bndbox.find('xmax').text = str("{:.2f}".format(bbox[1]))
# bndbox.find('ymin').text = str("{:.2f}".format(bbox[2]))
# bndbox.find('ymax').text = str("{:.2f}".format(bbox[3]))
new_xml = new_image_name.split('.')[0]+'.xml'
os.chdir(new_annotations_path)
my_tree.write(new_xml)
def save_aug_image(filename,image):
# new_images_path = '/Users/student/Work/IIQ/Augmentations_fire_kurle/new_ims'
# print(image.dtype)
im = Image.fromarray(image)
os.chdir(new_images_path)
im.save(filename)
def main_call():
# defining the transforms
# TRANSFORMS
transform = A.Compose([
# A.Resize(width = 1920,height=1080),
A.HorizontalFlip(p=0.5),
A.RGBShift(r_shift_limit=20,g_shift_limit=20,b_shift_limit=20,p=0.5),
A.OneOf([
A.Blur(blur_limit =3,p=0.4),
A.ColorJitter(brightness=0.3,contrast=0.2,p=0.4),
],p=0.4),
A.Rotate(limit = 30,p=0.4)
],bbox_params = A.BboxParams(format ='pascal_voc'))
# #############
# images_path = '/Users/student/Work/IIQ/Augmentations_fire_kurle/Fire_Detection-2/Images'
# annotations_path = '/Users/student/Work/IIQ/Augmentations_fire_kurle/Fire_Detection-2/XML'
images = os.listdir(images_path)
annotations = os.listdir(annotations_path)
i=0
for image in images:
i+=1
if i==2:
print("done test")
break
img = readImage(image)
ann_path = image.split('.')[0]+'.xml'
annotation = annotations[annotations.index(ann_path)]
bbox = getCoordinates(annotation)
# print("aaa")
# print(bbox)
# print("bbb")
images_list = []
saved_bbox = []
for i in range(35):
augmentations = transform(image= img , bboxes = bbox)
augmented_img = augmentations['image']
images_list.append(augmented_img)
saved_bbox.append(augmentations['bboxes'])
new_filename = image.split('.')[0]+'_'+str(i)+'.jpg'
save_aug_image(new_filename,augmented_img)
modifyXML_andSave(annotation,new_filename,augmentations['bboxes'])
print("xml and image saved for image "+new_filename)
# print(len(augmentations['bboxes']))
# plotExamples(images_list,saved_bbox)
# print(saved_bbox)
if __name__ == '__main__':
# getCoordinates('/content/drive/MyDrive/Augmentations/annotations/hm_0.xml')
main_call()