[54586b]: / DataAugmentation / DatAug.py

Download this file

556 lines (488 with data), 21.9 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
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
dataPath = "../Data_postiveOnly/"
import os
print(os.getcwd())
import imgaug as ia
import skimage.io
import errno
import numpy as np
import skimage.color as color
#import matplotlib.pyplot as plt
import os
#from skimage.color import gray2rgb
def bboxSetupInImage(datapath, txtFile, img):
"""
This is the function that reads in the bounding box files and then using imgaug to set up the bounding box on images
:param txtFile: the txt file that store bounding box information
:param img: the image file variable to represent the img to be plotted bounding box on it
:return bbs: the image with bounding box in it
"""
with open(datapath + 'bounding_boxes/' + txtFile, 'r') as f:
content = [line.rstrip('\n') for line in f]
iaBBoxList = []
for bbline in content:
bbox = bbline.strip().split()
# print(bbox[1])
if len(bbox) == 4:
iaBBoxList.append(ia.BoundingBox(
x1=float(bbox[1]),
y1=float(bbox[0]),
x2=float(bbox[3]),
y2=float(bbox[2])))
bbs = ia.BoundingBoxesOnImage(iaBBoxList, shape=img.shape)
return bbs
def saveAugbbox2TXT(txtFile, bbs):
"""
This is the function that save the augmented bounding box files into ChainerCV bbox format
:param txtFile: the txt file that want to save
:param bbs: bounding box lists
"""
with open('' + txtFile, 'w') as f:
for i in range(len(bbs.bounding_boxes)):
bb = bbs_aug.bounding_boxes[i]
# print("%s %.2f %.2f %.2f %.2f"%(bb.label,bb.y1,bb.x1,bb.y2,bb.x2))
f.write("%.2f %.2f %.2f %.2f\n" % ( bb.y1, bb.x1, bb.y2, bb.x2))
def getImageList(imageTXT):
"""
Function to loop the testing images for test
:param imageTXT: the txt that stores the
:return: imageFileList: the list contains all the original test image list
"""
imageFileList = list()
with open(imageTXT,'r') as f:
lines = f.readlines()
for line in lines:
imageFileList.append(line.strip())
return imageFileList
def createFolder(folderName):
"""
Safely create folder when needed
:param folderName : the directory that you want to safely create
:return: None
"""
if not os.path.exists(folderName):
try:
os.makedirs(folderName)
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
##################################################
# 1. Define data augmentation operations
##################################################
trainImageTxtFile = dataPath + "trainimages.txt"
imageList = getImageList(trainImageTxtFile)
current_operation = "GaussianNoise"
# Add gaussian noise.
# For 50% of all images, we sample the noise once per pixel.
# For the other 50% of all images, we sample the noise per pixel AND
# channel. This can change the color (not only brightness) of the
# pixels.
from imgaug import augmenters as iaa
ia.seed(1)
seq = iaa.Sequential([
iaa.AdditiveGaussianNoise(loc=0,
scale=(0.0, 0.01 * 255),
per_channel=0.5)
])
# seq = iaa.Sequential([
# # Adjust contrast by scaling each pixel value to (I_ij/255.0)**gamma.
# # Values in the range gamma=(0.5, 2.0) seem to be sensible.
# iaa.GammaContrast((0.5, 1.5))
# ])
# Make our sequence deterministic.
# We can now apply it to the image and then to the BBs and it will
# lead to the same augmentations.
# IMPORTANT: Call this once PER BATCH, otherwise you will always get the exactly same augmentations for every batch!
seq_det = seq.to_deterministic()
##################################################
# 2. loop through images
##################################################
for img in imageList:
print(img)
# Grayscale images must have shape (height, width, 1) each.
# print(os.listdir(dataPath+'images/'))
currentimage = skimage.io.imread(dataPath + 'images/' + img).astype(np.uint8)
# gray2rgb() simply duplicates the gray values over the three color channels.
currentimage = color.gray2rgb(currentimage)
bbs = bboxSetupInImage(dataPath, img.rstrip('.jpg') + '.txt', currentimage)
# Augment BBs and images.
# As we only have one image and list of BBs, we use
# [image] and [bbs] to turn both into lists (batches) for the# functions and then [0] to reverse that. In a real experiment, your
# variables would likely already be lists.
image_aug = seq_det.augment_images([currentimage])[0]
bbs_aug = seq_det.augment_bounding_boxes([bbs])[0]
print(bbs_aug)
augImgFolder = current_operation + "Images"
augTxTFolder = current_operation + "TXT"
createFolder(augImgFolder)
createFolder(augTxTFolder)
# Save aug images and bboxes
skimage.io.imsave(augImgFolder + '/' +
img.rstrip('.jpg') +
'_' + current_operation +
'.jpg'
, image_aug)
saveAugbbox2TXT(augTxTFolder + '/' +
img.rstrip('.jpg') +
'_' + current_operation +
'.txt', bbs_aug)
# image with BBs before/after augmentation (shown below)
# image_before = bbs.draw_on_image(currentimage, thickness=2)
# image_after = bbs_aug.draw_on_image(image_aug,
# thickness=2, color=[0, 0, 255])
# image with BBs before/after augmentation (shown below)
# plot and save figures before and after data augmentations
# skimage.io.imshow(image_before)
# skimage.io.imshow(image_after)
# for i in range(len(bbs.bounding_boxes)):
# before = bbs.bounding_boxes[i]
# after = bbs_aug.bounding_boxes[i]
# print("BB %d: (%.4f, %.4f, %.4f, %.4f) -> (%.4f, %.4f, %.4f, %.4f)" % (
# i,
# before.x1, before.y1, before.x2, before.y2,
# after.x1, after.y1, after.x2, after.y2)
# )
##################################################
# 1. Define data augmentation operations
##################################################
trainImageTxtFile = dataPath + "trainimages.txt"
imageList = getImageList(trainImageTxtFile)
current_operation = "GaussianBlur"
# blur images with a sigma of 0 to 3.0
from imgaug import augmenters as iaa
ia.seed(1)
seq = iaa.Sequential([
iaa.GaussianBlur(sigma=(0, 3))
])
# seq = iaa.Sequential([
# # Adjust contrast by scaling each pixel value to (I_ij/255.0)**gamma.
# # Values in the range gamma=(0.5, 2.0) seem to be sensible.
# iaa.GammaContrast((0.5, 1.5))
# ])
# Make our sequence deterministic.
# We can now apply it to the image and then to the BBs and it will
# lead to the same augmentations.
# IMPORTANT: Call this once PER BATCH, otherwise you will always get the exactly same augmentations for every batch!
seq_det = seq.to_deterministic()
##################################################
# 2. loop through images
##################################################
for img in imageList:
print(img)
# Grayscale images must have shape (height, width, 1) each.
#print(os.listdir(dataPath+'images/'))
currentimage = skimage.io.imread(dataPath+'images/'+img).astype(np.uint8)
# gray2rgb() simply duplicates the gray values over the three color channels.
currentimage = color.gray2rgb(currentimage)
bbs = bboxSetupInImage(dataPath , img.rstrip('.jpg') + '.txt',currentimage)
# Augment BBs and images.
# As we only have one image and list of BBs, we use
# [image] and [bbs] to turn both into lists (batches) for the# functions and then [0] to reverse that. In a real experiment, your
# variables would likely already be lists.
image_aug = seq_det.augment_images([currentimage])[0]
bbs_aug = seq_det.augment_bounding_boxes([bbs])[0]
augImgFolder = current_operation + "Images"
augTxTFolder = current_operation + "TXT"
createFolder(augImgFolder)
createFolder(augTxTFolder)
# Save aug images and bboxes
skimage.io.imsave(augImgFolder + '/'+
img.rstrip('.jpg') +
'_' + current_operation +
'.jpg'
,image_aug)
saveAugbbox2TXT(augTxTFolder+ '/'+
img.rstrip('.jpg') +
'_'+ current_operation +
'.txt',bbs_aug)
# image with BBs before/after augmentation (shown below)
# image_before = bbs.draw_on_image(currentimage, thickness=2)
# image_after = bbs_aug.draw_on_image(image_aug,
# thickness=2, color=[0, 0, 255])
# image with BBs before/after augmentation (shown below)
# plot and save figures before and after data augmentations
#skimage.io.imshow(image_before)
#skimage.io.imshow(image_after)
# for i in range(len(bbs.bounding_boxes)):
# before = bbs.bounding_boxes[i]
# after = bbs_aug.bounding_boxes[i]
# print("BB %d: (%.4f, %.4f, %.4f, %.4f) -> (%.4f, %.4f, %.4f, %.4f)" % (
# i,
# before.x1, before.y1, before.x2, before.y2,
# after.x1, after.y1, after.x2, after.y2)
# )
##################################################
# 1. Define data augmentation operations
##################################################
trainImageTxtFile = dataPath + "trainimages.txt"
imageList = getImageList(trainImageTxtFile)
current_operation = "Brightness"
# Strengthen or weaken the contrast in each image.
from imgaug import augmenters as iaa
ia.seed(1)
seq = iaa.Sequential([
iaa.Multiply((1.2, 1.5))
])
# seq = iaa.Sequential([
# # Adjust contrast by scaling each pixel value to (I_ij/255.0)**gamma.
# # Values in the range gamma=(0.5, 2.0) seem to be sensible.
# iaa.GammaContrast((0.5, 1.5))
# ])
# Make our sequence deterministic.
# We can now apply it to the image and then to the BBs and it will
# lead to the same augmentations.
# IMPORTANT: Call this once PER BATCH, otherwise you will always get the exactly same augmentations for every batch!
seq_det = seq.to_deterministic()
##################################################
# 2. loop through images
##################################################
for img in imageList:
print(img)
# Grayscale images must have shape (height, width, 1) each.
#print(os.listdir(dataPath+'images/'))
currentimage = skimage.io.imread(dataPath+'images/'+img).astype(np.uint8)
# gray2rgb() simply duplicates the gray values over the three color channels.
currentimage = color.gray2rgb(currentimage)
bbs = bboxSetupInImage(dataPath , img.rstrip('.jpg') + '.txt',currentimage)
# Augment BBs and images.
# As we only have one image and list of BBs, we use
# [image] and [bbs] to turn both into lists (batches) for the# functions and then [0] to reverse that. In a real experiment, your
# variables would likely already be lists.
image_aug = seq_det.augment_images([currentimage])[0]
bbs_aug = seq_det.augment_bounding_boxes([bbs])[0]
augImgFolder = current_operation + "Images"
augTxTFolder = current_operation + "TXT"
createFolder(augImgFolder)
createFolder(augTxTFolder)
# Save aug images and bboxes
skimage.io.imsave(augImgFolder + '/'+
img.rstrip('.jpg') +
'_' + current_operation +
'.jpg'
,image_aug)
saveAugbbox2TXT(augTxTFolder+ '/'+
img.rstrip('.jpg') +
'_'+ current_operation +
'.txt',bbs_aug)
# image with BBs before/after augmentation (shown below)
# image_before = bbs.draw_on_image(currentimage, thickness=2)
# image_after = bbs_aug.draw_on_image(image_aug,
# thickness=2, color=[0, 0, 255])
# image with BBs before/after augmentation (shown below)
# plot and save figures before and after data augmentations
#skimage.io.imshow(image_before)
#skimage.io.imshow(image_after)
# for i in range(len(bbs.bounding_boxes)):
# before = bbs.bounding_boxes[i]
# after = bbs_aug.bounding_boxes[i]
# print("BB %d: (%.4f, %.4f, %.4f, %.4f) -> (%.4f, %.4f, %.4f, %.4f)" % (
# i,
# before.x1, before.y1, before.x2, before.y2,
# after.x1, after.y1, after.x2, after.y2)
# )
##################################################
# 1. Define data augmentation operations
##################################################
trainImageTxtFile = dataPath + "trainimages.txt"
imageList = getImageList(trainImageTxtFile)
current_operation = "Fliplr"
# Flip/mirror input images horizontally.
from imgaug import augmenters as iaa
ia.seed(1)
seq = iaa.Sequential([
iaa.Fliplr(1.0)
])
# seq = iaa.Sequential([
# # Adjust contrast by scaling each pixel value to (I_ij/255.0)**gamma.
# # Values in the range gamma=(0.5, 2.0) seem to be sensible.
# iaa.GammaContrast((0.5, 1.5))
# ])
# Make our sequence deterministic.
# We can now apply it to the image and then to the BBs and it will
# lead to the same augmentations.
# IMPORTANT: Call this once PER BATCH, otherwise you will always get the exactly same augmentations for every batch!
seq_det = seq.to_deterministic()
##################################################
# 2. loop through images
##################################################
for img in imageList:
print(img)
# Grayscale images must have shape (height, width, 1) each.
# print(os.listdir(dataPath+'images/'))
currentimage = skimage.io.imread(dataPath + 'images/' + img).astype(np.uint8)
# gray2rgb() simply duplicates the gray values over the three color channels.
currentimage = color.gray2rgb(currentimage)
bbs = bboxSetupInImage(dataPath, img.rstrip('.jpg') + '.txt', currentimage)
# Augment BBs and images.
# As we only have one image and list of BBs, we use
# [image] and [bbs] to turn both into lists (batches) for the# functions and then [0] to reverse that. In a real experiment, your
# variables would likely already be lists.
image_aug = seq_det.augment_images([currentimage])[0]
bbs_aug = seq_det.augment_bounding_boxes([bbs])[0]
augImgFolder = current_operation + "Images"
augTxTFolder = current_operation + "TXT"
createFolder(augImgFolder)
createFolder(augTxTFolder)
# Save aug images and bboxes
skimage.io.imsave(augImgFolder + '/' +
img.rstrip('.jpg') +
'_' + current_operation +
'.jpg'
, image_aug)
saveAugbbox2TXT(augTxTFolder + '/' +
img.rstrip('.jpg') +
'_' + current_operation +
'.txt', bbs_aug)
# image with BBs before/after augmentation (shown below)
# image_before = bbs.draw_on_image(currentimage, thickness=2)
# image_after = bbs_aug.draw_on_image(image_aug,
# thickness=2, color=[0, 0, 255])
# image with BBs before/after augmentation (shown below)
# plot and save figures before and after data augmentations
# skimage.io.imshow(image_before)
# skimage.io.imshow(image_after)
# for i in range(len(bbs.bounding_boxes)):
# before = bbs.bounding_boxes[i]
# after = bbs_aug.bounding_boxes[i]
# print("BB %d: (%.4f, %.4f, %.4f, %.4f) -> (%.4f, %.4f, %.4f, %.4f)" % (
# i,
# before.x1, before.y1, before.x2, before.y2,
# after.x1, after.y1, after.x2, after.y2)
# )
##################################################
# 1. Define data augmentation operations
##################################################
trainImageTxtFile = dataPath + "trainimages.txt"
imageList = getImageList(trainImageTxtFile)
current_operation = "Flipud"
# Flip/mirror input images vertically.
from imgaug import augmenters as iaa
ia.seed(1)
seq = iaa.Sequential([
iaa.Flipud(1.0)
])
# seq = iaa.Sequential([
# # Adjust contrast by scaling each pixel value to (I_ij/255.0)**gamma.
# # Values in the range gamma=(0.5, 2.0) seem to be sensible.
# iaa.GammaContrast((0.5, 1.5))
# ])
# Make our sequence deterministic.
# We can now apply it to the image and then to the BBs and it will
# lead to the same augmentations.
# IMPORTANT: Call this once PER BATCH, otherwise you will always get the exactly same augmentations for every batch!
seq_det = seq.to_deterministic()
##################################################
# 2. loop through images
##################################################
for img in imageList:
print(img)
# Grayscale images must have shape (height, width, 1) each.
# print(os.listdir(dataPath+'images/'))
currentimage = skimage.io.imread(dataPath + 'images/' + img).astype(np.uint8)
# gray2rgb() simply duplicates the gray values over the three color channels.
currentimage = color.gray2rgb(currentimage)
bbs = bboxSetupInImage(dataPath, img.rstrip('.jpg') + '.txt', currentimage)
# Augment BBs and images.
# As we only have one image and list of BBs, we use
# [image] and [bbs] to turn both into lists (batches) for the# functions and then [0] to reverse that. In a real experiment, your
# variables would likely already be lists.
image_aug = seq_det.augment_images([currentimage])[0]
bbs_aug = seq_det.augment_bounding_boxes([bbs])[0]
augImgFolder = current_operation + "Images"
augTxTFolder = current_operation + "TXT"
createFolder(augImgFolder)
createFolder(augTxTFolder)
# Save aug images and bboxes
skimage.io.imsave(augImgFolder + '/' +
img.rstrip('.jpg') +
'_' + current_operation +
'.jpg'
, image_aug)
saveAugbbox2TXT(augTxTFolder + '/' +
img.rstrip('.jpg') +
'_' + current_operation +
'.txt', bbs_aug)
# image with BBs before/after augmentation (shown below)
# image_before = bbs.draw_on_image(currentimage, thickness=2)
# image_after = bbs_aug.draw_on_image(image_aug,
# thickness=2, color=[0, 0, 255])
# image with BBs before/after augmentation (shown below)
# plot and save figures before and after data augmentations
# skimage.io.imshow(image_before)
# skimage.io.imshow(image_after)
# for i in range(len(bbs.bounding_boxes)):
# before = bbs.bounding_boxes[i]
# after = bbs_aug.bounding_boxes[i]
# print("BB %d: (%.4f, %.4f, %.4f, %.4f) -> (%.4f, %.4f, %.4f, %.4f)" % (
# i,
# before.x1, before.y1, before.x2, before.y2,
# after.x1, after.y1, after.x2, after.y2)
# )
##################################################
# 1. Define data augmentation operations
##################################################
trainImageTxtFile = dataPath + "trainimages.txt"
imageList = getImageList(trainImageTxtFile)
current_operation = "Rot90or270Degree"
# Rotates all images by 90 or 270 degrees.
from imgaug import augmenters as iaa
ia.seed(1)
seq = iaa.Sequential([
iaa.Rot90([1, 3])
])
# seq = iaa.Sequential([
# # Adjust contrast by scaling each pixel value to (I_ij/255.0)**gamma.
# # Values in the range gamma=(0.5, 2.0) seem to be sensible.
# iaa.GammaContrast((0.5, 1.5))
# ])
# Make our sequence deterministic.
# We can now apply it to the image and then to the BBs and it will
# lead to the same augmentations.
# IMPORTANT: Call this once PER BATCH, otherwise you will always get the exactly same augmentations for every batch!
seq_det = seq.to_deterministic()
##################################################
# 2. loop through images
##################################################
for img in imageList:
print(img)
# Grayscale images must have shape (height, width, 1) each.
# print(os.listdir(dataPath+'images/'))
currentimage = skimage.io.imread(dataPath + 'images/' + img).astype(np.uint8)
# gray2rgb() simply duplicates the gray values over the three color channels.
currentimage = color.gray2rgb(currentimage)
bbs = bboxSetupInImage(dataPath, img.rstrip('.jpg') + '.txt', currentimage)
# Augment BBs and images.
# As we only have one image and list of BBs, we use
# [image] and [bbs] to turn both into lists (batches) for the# functions and then [0] to reverse that. In a real experiment, your
# variables would likely already be lists.
image_aug = seq_det.augment_images([currentimage])[0]
bbs_aug = seq_det.augment_bounding_boxes([bbs])[0]
augImgFolder = current_operation + "Images"
augTxTFolder = current_operation + "TXT"
createFolder(augImgFolder)
createFolder(augTxTFolder)
# Save aug images and bboxes
skimage.io.imsave(augImgFolder + '/' +
img.rstrip('.jpg') +
'_' + current_operation +
'.jpg'
, image_aug)
saveAugbbox2TXT(augTxTFolder + '/' +
img.rstrip('.jpg') +
'_' + current_operation +
'.txt', bbs_aug)
# image with BBs before/after augmentation (shown below)
# image_before = bbs.draw_on_image(currentimage, thickness=2)
# image_after = bbs_aug.draw_on_image(image_aug,
# thickness=2, color=[0, 0, 255])
# image with BBs before/after augmentation (shown below)
# plot and save figures before and after data augmentations
# skimage.io.imshow(image_before)
# skimage.io.imshow(image_after)
# for i in range(len(bbs.bounding_boxes)):
# before = bbs.bounding_boxes[i]
# after = bbs_aug.bounding_boxes[i]
# print("BB %d: (%.4f, %.4f, %.4f, %.4f) -> (%.4f, %.4f, %.4f, %.4f)" % (
# i,
# before.x1, before.y1, before.x2, before.y2,
# after.x1, after.y1, after.x2, after.y2)
# )