forked from debidatta/syndata-generation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataset_generator.py
1737 lines (1301 loc) · 58.2 KB
/
dataset_generator.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
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import glob
import sys
import os
from xml.etree.ElementTree import Element, SubElement, tostring
import xml.dom.minidom
import cv2
import numpy as np
import random
from PIL import Image, ImageDraw
import scipy
from multiprocessing import Pool
from multiprocessing import get_context
from functools import partial
import signal
import time
import json
from datetime import datetime
import csv
import shutil
from defaults import *
sys.path.insert(0, POISSON_BLENDING_DIR)
from pb import *
import math
from pyblur3 import *
from collections import namedtuple
from pycocotools.coco import COCO
from itertools import combinations
Rectangle = namedtuple('Rectangle', 'xmin ymin xmax ymax')
def randomAngle(kerneldim):
"""Returns a random angle used to produce motion blurring
Args:
kerneldim (int): size of the kernel used in motion blurring
Returns:
int: Random angle
"""
kernelCenter = int(math.floor(kerneldim/2))
numDistinctLines = kernelCenter * 4
validLineAngles = np.linspace(0,180, numDistinctLines, endpoint = False)
angleIdx = np.random.randint(0, len(validLineAngles))
return int(validLineAngles[angleIdx])
def LinearMotionBlur3C(img):
"""Performs motion blur on an image with 3 channels. Used to simulate
blurring caused due to motion of camera.
Args:
img(NumPy Array): Input image with 3 channels
Returns:
Image: Blurred image by applying a motion blur with random parameters
"""
lineLengths = [3,5,7,9]
lineTypes = ["right", "left", "full"]
lineLengthIdx = np.random.randint(0, len(lineLengths))
lineTypeIdx = np.random.randint(0, len(lineTypes))
lineLength = lineLengths[lineLengthIdx]
lineType = lineTypes[lineTypeIdx]
lineAngle = randomAngle(lineLength)
blurred_img = img
for i in range(3):
blurred_img[:,:,i] = PIL2array1C(LinearMotionBlur(img[:,:,i], lineLength, lineAngle, lineType))
blurred_img = Image.fromarray(blurred_img, 'RGB')
return blurred_img
def overlap(a, b, max_allowed_iou):
'''Find if two bounding boxes are overlapping or not. This is determined by maximum allowed
IOU between bounding boxes. If IOU is less than the max allowed IOU then bounding boxes
don't overlap
Args:
a(Rectangle): Bounding box 1
b(Rectangle): Bounding box 2
Returns:
bool: True if boxes overlap else False
'''
dx = min(a.xmax, b.xmax) - max(a.xmin, b.xmin)
dy = min(a.ymax, b.ymax) - max(a.ymin, b.ymin)
if (dx>=0) and (dy>=0) and float(dx*dy) > max_allowed_iou*(a.xmax-a.xmin)*(a.ymax-a.ymin):
return True
else:
return False
def get_list_of_images(root_dir):
'''Gets the list of images of objects in the root directory. The expected format
is root_dir/<object>/<image>.jpg. Adds an image as many times you want it to
appear in dataset.
Args:
root_dir(string): Directory where images of objects are present
N(int): Number of times an image would appear in dataset. Each image should have
different data augmentation
Returns:
list: List of images(with paths) that will be put in the dataset
'''
img_list = glob.glob(os.path.join(root_dir, '*/*_mask.jpg'))
if (len(img_list) == 0):
img_list = glob.glob(os.path.join(root_dir, '*/*.jpg'))
else:
img_list = [img.replace("_mask", "") for img in img_list]
return img_list
def get_mask_file(img_file):
'''Takes an image file name and returns the corresponding mask file. The mask represents
pixels that belong to the object. Default implentation assumes mask file has same path
as image file with different extension only. Write custom code for getting mask file here
if this is not the case.
Args:
img_file(string): Image name
Returns:
string: Correpsonding mask file path
'''
mask_file = img_file.replace('.jpg','_mask.jpg')
return mask_file
def get_labels(imgs):
'''Get list of labels/object names. Assumes the images in the root directory follow root_dir/<object>/<image>
structure. Directory name would be object name.
Args:
imgs(list): List of images being used for synthesis
Returns:
list: List of labels/object names corresponding to each image
'''
labels = []
for img_file in imgs:
img_file = img_file.replace("\\", "/")
label = img_file.split('/')[-2]
labels.append(label)
return labels
def get_annotation_from_mask_file(mask_file, scale=1.0):
'''Given a mask file and scale, return the bounding box annotations
Args:
mask_file(string): Path of the mask file
Returns:
tuple: Bounding box annotation (xmin, xmax, ymin, ymax)
'''
if os.path.exists(mask_file):
mask = cv2.imread(mask_file)
if INVERTED_MASK:
mask = 255 - mask
rows = np.any(mask, axis=1)
cols = np.any(mask, axis=0)
if len(np.where(rows)[0]) > 0:
ymin, ymax = np.where(rows)[0][[0, -1]]
xmin, xmax = np.where(cols)[0][[0, -1]]
return int(scale*xmin), int(scale*xmax), int(scale*ymin), int(scale*ymax)
else:
return -1, -1, -1, -1
else:
print ("%s not found. Using empty mask instead." % mask_file)
return -1, -1, -1, -1
def get_annotation_from_mask(mask):
'''Given a mask, this returns the bounding box annotations
Args:
mask(NumPy Array): Array with the mask
Returns:
tuple: Bounding box annotation (xmin, xmax, ymin, ymax)
'''
rows = np.any(mask, axis=1)
cols = np.any(mask, axis=0)
if len(np.where(rows)[0]) > 0:
ymin, ymax = np.where(rows)[0][[0, -1]]
xmin, xmax = np.where(cols)[0][[0, -1]]
return xmin, xmax, ymin, ymax
else:
return -1, -1, -1, -1
def PIL2array1C(img):
'''Converts a PIL image to NumPy Array
Args:
img(PIL Image): Input PIL image
Returns:
NumPy Array: Converted image
'''
return np.array(img.getdata(),
np.uint8).reshape(img.size[1], img.size[0])
def PIL2array3C(img):
'''Converts a PIL image to NumPy Array
Args:
img(PIL Image): Input PIL image
Returns:
NumPy Array: Converted image
'''
return np.array(img.getdata(),
np.uint8).reshape(img.size[1], img.size[0], 3)
def create_image_anno_wrapper(objects, args):
''' Wrapper used to pass params to workers
'''
return create_image_anno(*objects, args)
def create_image_anno_spatial_pairs_wrapper(objects, args):
''' Wrapper used to pass params to workers
'''
return create_image_spatial_pairs_anno(*objects, args)
def create_image_anno_spatial_wrapper(objects, args):
''' Wrapper used to pass params to workers
'''
return create_image_spatial_anno(*objects, args)
def crop_resize(im, desired_size):
old_size = im.size # old_size[0] is in (width, height) format
ratio = max(desired_size)/min(old_size)
new_size = tuple([int(x*ratio) for x in old_size])
# use thumbnail() or resize() method to resize the input image
# thumbnail is a in-place operation
# im.thumbnail(new_size, Image.Resampling.LANCZOS)
im = im.resize(new_size, Image.Resampling.LANCZOS)
# create a new image and paste the resized on it
new_im = Image.new("RGB", (desired_size[0], desired_size[1]))
new_im.paste(im, ((desired_size[0]-new_size[0])//2,
(desired_size[1]-new_size[1])//2))
return new_im
def create_coco_annotation(xmin, ymin, xmax, ymax, image_id, obj, annotation_id):
annotation = {
'iscrowd': False,
'image_id': image_id,
'category_id': obj,
'id': annotation_id,
'bbox': [xmin, ymin, xmax-xmin, ymax-ymin],
'area': (xmax-xmin)*(ymax-ymin)
}
return annotation
def render_objects(backgrounds, all_objects, min_scale, max_scale, args, already_syn=[], annotations=None, image_id=None):
blending_list = args.blending_list
w = args.width
h = args.height
max_scale = min(max_scale,1.0)
rendered = False
annotation_id = 0
for idx, obj in enumerate(all_objects):
if (os.path.isfile(obj[0])):
foreground = Image.open(obj[0])
else:
foreground = Image.open(obj[0].replace("jpg", "JPEG"))
xmin, xmax, ymin, ymax = get_annotation_from_mask_file(get_mask_file(obj[0]))
if xmin == -1 or ymin == -1 or xmax-xmin < args.min_width or ymax-ymin < args.min_height :
continue
foreground = foreground.crop((xmin, ymin, xmax, ymax))
orig_w, orig_h = foreground.size
mask_file = get_mask_file(obj[0])
mask = Image.open(mask_file)
mask = mask.crop((xmin, ymin, xmax, ymax))
if INVERTED_MASK:
mask = Image.fromarray(255-PIL2array1C(mask)).convert('1')
o_w, o_h = orig_w, orig_h
additional_scale = min(w/o_w,h/o_h)
if args.scale:
attempt_scale = 0
while True:
attempt_scale +=1
frot
if (args.stats and image_id):
scale = np.clip(1-np.random.lognormal(args.stats["s"]["mean"], args.stats["s"]["std"]), min_scale, max_scale)*additional_scale
else:
scale = random.uniform(min_scale, max_scale)*additional_scale
o_w, o_h = int(scale*orig_w), int(scale*orig_h)
if w-o_w > 0 and h-o_h > 0 and o_w > 0 and o_h > 0:
foreground = foreground.resize((o_w, o_h), Image.Resampling.LANCZOS)
mask = mask.resize((o_w, o_h), Image.Resampling.LANCZOS)
break
if attempt_scale == MAX_ATTEMPTS_TO_SYNTHESIZE:
o_w = w
o_h = h
foreground = foreground.resize((o_w, o_h), Image.Resampling.LANCZOS)
mask = mask.resize((o_w, o_h), Image.Resampling.LANCZOS)
break
if args.rotation:
max_degrees = args.max_degrees
attempt_rotation = 0
while True:
attempt_rotation +=1
rot_degrees = random.randint(-max_degrees, max_degrees)
foreground_tmp = foreground.rotate(rot_degrees, expand=True)
mask_tmp = mask.rotate(rot_degrees, expand=True)
o_w, o_h = foreground_tmp.size
if w-o_w > 0 and h-o_h > 0:
mask = mask_tmp
foreground = foreground_tmp
break
if attempt_rotation == MAX_ATTEMPTS_TO_SYNTHESIZE:
o_w, o_h = foreground.size
break
xmin, xmax, ymin, ymax = get_annotation_from_mask(mask)
attempt_place = 0
while True:
attempt_place +=1
# gaussian perterb from placing centered
if (args.stats and image_id):
x = int(w/2-(xmax-xmin)/2) + int(np.random.normal(args.stats["x"]["mean"]*w, args.stats["x"]["std"]*w))
y = int(h/2-(ymax-ymin)/2) + int(np.random.normal(args.stats["y"]["mean"]*h, args.stats["y"]["std"]*h))
elif (args.gaussian_trans):
x = int(w/2-(xmax-xmin)/2) + int(np.random.normal(args.gaussian_trans_mean[0]*w, args.gaussian_trans_std[0]*w))
y = int(h/2-(ymax-ymin)/2) + int(np.random.normal(args.gaussian_trans_mean[1]*h, args.gaussian_trans_std[1]*h))
else:
x = random.randint(int(-args.max_truncation_fraction*o_w), int(w-o_w+args.max_truncation_fraction*o_w))
y = random.randint(int(-args.max_truncation_fraction*o_h), int(h-o_h+args.max_truncation_fraction*o_h))
found = True
if args.dontocclude:
for prev in already_syn:
ra = Rectangle(prev[0], prev[2], prev[1], prev[3])
rb = Rectangle(x+xmin, y+ymin, x+xmax, y+ymax)
if overlap(ra, rb, args.max_allowed_iou):
found = False
break
if found:
break
else:
break
if attempt_place == MAX_ATTEMPTS_TO_SYNTHESIZE:
break
if (found):
if args.dontocclude:
already_syn.append([x+xmin, x+xmax, y+ymin, y+ymax])
rendered = True
for i in range(len(blending_list)):
if blending_list[i] == 'none' or blending_list[i] == 'motion':
backgrounds[i].paste(foreground, (x, y), mask)
elif blending_list[i] == 'poisson':
offset = (y, x)
img_mask = PIL2array1C(mask)
img_src = PIL2array3C(foreground).astype(np.float64)
img_target = PIL2array3C(backgrounds[i])
img_mask, img_src, offset_adj \
= create_mask(img_mask.astype(np.float64),
img_target, img_src, offset=offset)
background_array = poisson_blend(img_mask, img_src, img_target,
method='normal', offset_adj=offset_adj)
backgrounds[i] = Image.fromarray(background_array, 'RGB')
elif blending_list[i] == 'gaussian':
backgrounds[i].paste(foreground, (x, y), Image.fromarray(cv2.GaussianBlur(PIL2array1C(mask),(5,5),2)))
elif blending_list[i] == 'box':
backgrounds[i].paste(foreground, (x, y), Image.fromarray(cv2.blur(PIL2array1C(mask),(3,3))))
if (annotations is not None):
xmin = int(max(1,xmin))
ymin = int(max(1,ymin))
xmax = int(min(w,xmax))
ymax = int(min(h,ymax))
annotation = create_coco_annotation(xmin, ymin, xmax, ymax, image_id, str(obj[1]), annotation_id)
annotations.append(annotation)
annotation_id += 1
return rendered, already_syn, annotations
def render_object_spatial(img, args):
w = args.width
h = args.height
if (os.path.isfile(img)):
foreground = Image.open(img)
else:
foreground = Image.open(img.replace("jpg", "JPEG"))
mask_file = get_mask_file(img)
xmin, xmax, ymin, ymax = get_annotation_from_mask_file(mask_file)
mask = Image.open(mask_file)
#foreground.show()
#mask.show()
foreground = foreground.crop((xmin, ymin, xmax, ymax))
orig_w, orig_h = foreground.size
mask = mask.crop((xmin, ymin, xmax, ymax))
if INVERTED_MASK:
mask = Image.fromarray(255-PIL2array1C(mask)).convert('1')
o_w, o_h = orig_w, orig_h
#foreground.show()
#mask.show()
additional_scale = min(0.4*w/o_w,0.4*h/o_h)
if args.scale:
scale = random.uniform(args.min_scale, args.max_scale)*additional_scale
else:
scale = additional_scale
o_w, o_h = int(scale*orig_w), int(scale*orig_h)
foreground = foreground.resize((o_w, o_h), Image.Resampling.LANCZOS)
mask = mask.resize((o_w, o_h), Image.Resampling.LANCZOS)
#foreground.show()
#mask.show()
if args.rotation:
rot_degrees = random.randint(-args.max_degrees, args.max_degrees)
foreground = foreground.rotate(rot_degrees, expand=True)
mask = mask.rotate(rot_degrees, expand=True)
xmin, xmax, ymin, ymax = get_annotation_from_mask(mask)
foreground = foreground.crop((xmin, ymin, xmax, ymax))
mask = mask.crop((xmin, ymin, xmax, ymax))
#foreground.show()
#mask.show()
return foreground, mask
def colorize_image(foregroundA, colorA):
if (colorA == "red"):
matrix = (2.5, 0, 0, 0,
0, .25, 0, 0,
0, 0, .25, 0)
foregroundA = foregroundA.convert("RGB", matrix)
elif (colorA == "green"):
matrix = (.25, 0, 0, 0,
0, 2.5, 0, 0,
0, 0, .25, 0)
foregroundA = foregroundA.convert("RGB", matrix)
elif (colorA == "blue"):
matrix = (.25, 0, 0, 0,
0, .25, 0, 0,
0, 0, 2.5, 0)
foregroundA = foregroundA.convert("RGB", matrix)
return foregroundA
def render_objects_spatial_pair(background, imgA, imgB, relation, colorA, colorB, args, image_id, annotations):
w = args.width
h = args.height
foregroundA, maskA = render_object_spatial(imgA, args)
foregroundB, maskB = render_object_spatial(imgB, args)
if (relation == "left"):
xA = w*.25
yA = h*.5
xB = w*.75
yB = h*.5
elif (relation == "right"):
xA = w*.75
yA = h*.5
xB = w*.25
yB = h*.5
elif (relation == "above"):
xA = w*.5
yA = h*.25
xB = w*.5
yB = h*.75
else:
xA = w*.5
yA = h*.75
xB = w*.5
yB = h*.25
if args.translation:
xA += random.uniform(-args.min_trans*w, args.min_trans*w)
yA += random.uniform(-args.min_trans*h, args.min_trans*h)
xB += random.uniform(-args.min_trans*w, args.min_trans*w)
yB += random.uniform(-args.min_trans*h, args.min_trans*h)
foregroundA = colorize_image(foregroundA, colorA)
foregroundB = colorize_image(foregroundB, colorB)
xAmin = int(xA-foregroundA.size[0]/2)
yAmin = int(yA-foregroundA.size[1]/2)
xAmax = xAmin+foregroundA.size[0]
yAmax = yAmin+foregroundA.size[1]
xBmin = int(xB-foregroundB.size[0]/2)
yBmin = int(yB-foregroundB.size[1]/2)
xBmax = xBmin+foregroundB.size[0]
yBmax = yBmin+foregroundB.size[1]
background.paste(foregroundA, (xAmin, yAmin), Image.fromarray(cv2.GaussianBlur(PIL2array1C(maskA),(5,5),2)))
background.paste(foregroundB, (xBmin, yBmin), Image.fromarray(cv2.GaussianBlur(PIL2array1C(maskB),(5,5),2)))
if (annotations is not None):
xAmin = int(max(1,xAmin))
yAmin = int(max(1,yAmin))
xAmax = int(min(w,xAmax))
yAmax = int(min(h,yAmax))
classA = os.path.dirname(imgA).split("\\")[-1]
annotation_id = 0
annotation = create_coco_annotation(xAmin, yAmin, xAmax, yAmax, image_id, classA, annotation_id)
annotations.append(annotation)
xBmin = int(max(1,xBmin))
yBmin = int(max(1,yBmin))
xBmax = int(min(w,xBmax))
yBmax = int(min(h,yBmax))
classB = os.path.dirname(imgB).split("\\")[-1]
annotation_id = 1
annotation = create_coco_annotation(xBmin, yBmin, xBmax, yBmax, image_id, classB, annotation_id)
annotations.append(annotation)
if (args.draw_boxes):
img = ImageDraw.Draw(background)
lineWidth = 4
xAmin = int(xA-foregroundA.size[0]/2)-lineWidth/2
yAmin = int(yA-foregroundA.size[1]/2)-lineWidth/2
xAmax = xAmin+foregroundA.size[0]+lineWidth
yAmax = yAmin+foregroundA.size[1]+lineWidth
img.rectangle([xAmin, yAmin, xAmax, yAmax], outline ="red", width=4)
xBmin = int(xB-foregroundB.size[0]/2)-lineWidth/2
yBmin = int(yB-foregroundB.size[1]/2)-lineWidth/2
xBmax = xBmin+foregroundB.size[0]+lineWidth
yBmax = yBmin+foregroundB.size[1]+lineWidth
img.rectangle([xBmin, yBmin, xBmax, yBmax], outline ="yellow", width=4)
#background.show()
return
def render_objects_spatial(background, imgA, relation, args, image_id, annotations):
w = args.width
h = args.height
foregroundA, maskA = render_object_spatial(imgA, args)
if (relation == "left"):
xA = w*.25
yA = h*.5
elif (relation == "right"):
xA = w*.75
yA = h*.5
elif (relation == "top"):
xA = w*.5
yA = h*.25
else:
xA = w*.5
yA = h*.75
if args.translation:
xA += random.uniform(-args.min_trans*w, args.min_trans*w)
yA += random.uniform(-args.min_trans*h, args.min_trans*h)
xAmin = int(xA-foregroundA.size[0]/2)
yAmin = int(yA-foregroundA.size[1]/2)
xAmax = xAmin+foregroundA.size[0]
yAmax = yAmin+foregroundA.size[1]
background.paste(foregroundA, (xAmin, yAmin), Image.fromarray(cv2.GaussianBlur(PIL2array1C(maskA),(5,5),2)))
xAmin = int(max(1,xAmin))
yAmin = int(max(1,yAmin))
xAmax = int(min(w,xAmax))
yAmax = int(min(h,yAmax))
classA = os.path.dirname(imgA).split("\\")[-1]
if (annotations is not None):
annotation_id = 0
annotation = create_coco_annotation(xAmin, yAmin, xAmax, yAmax, image_id, classA, annotation_id)
annotations.append(annotation)
if (args.draw_boxes):
img = ImageDraw.Draw(background)
lineWidth = 4
xAmin = int(xA-foregroundA.size[0]/2)-lineWidth/2
yAmin = int(yA-foregroundA.size[1]/2)-lineWidth/2
xAmax = xAmin+foregroundA.size[0]+lineWidth
yAmax = yAmin+foregroundA.size[1]+lineWidth
img.rectangle([xAmin, yAmin, xAmax, yAmax], outline ="red", width=4)
#background.show()
return
def create_image_anno(objects, distractor_objects, img_file, bg_file, image_id, args):
'''Add data augmentation, synthesizes images and generates annotations according to given parameters
Args:
objects(list): List of objects whose annotations are also important
distractor_objects(list): List of distractor objects that will be synthesized but whose annotations are not required
img_file(str): Image file name
anno_file(str): Annotation file name
bg_file(str): Background image path
'''
#if 'none' not in img_file:
# return
if (args.one_type_per_image):
img_file = os.path.join(objects[0][1], img_file)
print ("Working on %s" % img_file)
blending_list = args.blending_list
w = args.width
h = args.height
assert len(objects) > 0
annotations = []
img_info = {}
background = Image.open(bg_file)
background = crop_resize(background, (w, h))
backgrounds = []
for i in range(len(blending_list)):
backgrounds.append(background.copy())
if(args.add_backgroud_distractors and len(distractor_objects) > 0):
rendered, _, _ = render_objects(backgrounds, distractor_objects, args.min_distractor_scale, args.max_distractor_scale, args)
already_syn = []
rendered, already_syn, annotations = render_objects(backgrounds, objects, args.min_scale, args.max_scale, args, already_syn, annotations, image_id)
if (args.add_distractors and len(distractor_objects) > 0):
rendered, _, _ = render_objects(backgrounds, distractor_objects, args.min_distractor_scale, args.max_distractor_scale, args, already_syn)
if (rendered):
img_info["license"] = 0
img_info["file_name"] = img_file
img_info["width"] = w
img_info["height"] = h
img_info["id"] = image_id
img_file = os.path.join(args.exp, img_file)
for i in range(len(blending_list)):
if blending_list[i] == 'motion':
backgrounds[i] = LinearMotionBlur3C(PIL2array3C(backgrounds[i]))
backgrounds[i].save(img_file.replace('none', blending_list[i]))
return img_info, annotations
def create_image_spatial_pairs_anno(imgA, imgB, relation, backgroundImg, path, img_file, colorA, colorB, image_id, args):
img_file = os.path.join(path, img_file)
print ("Working on %s" % img_file)
blending_list = args.blending_list
w = args.width
h = args.height
annotations = []
#background = Image.new(mode="RGB", size=(w, h), color=(128, 128, 128))
background = Image.open(backgroundImg).resize((w, h))
render_objects_spatial_pair(background, imgA, imgB, relation, colorA, colorB, args, image_id, annotations)
os.makedirs(os.path.join(args.exp, path), exist_ok=True)
img_file_full = os.path.join(args.exp, img_file)
background.save(img_file_full)
img_info = {}
img_info["license"] = 0
img_info["file_name"] = img_file
img_info["width"] = w
img_info["height"] = h
img_info["id"] = image_id
return img_info, annotations
def create_image_spatial_anno(imgA, relation, backgroundImg, path, img_file, image_id, args):
img_file = os.path.join(path, img_file)
print ("Working on %s" % img_file)
blending_list = args.blending_list
w = args.width
h = args.height
annotations = []
img_info = {}
#background = Image.new(mode="RGB", size=(w, h), color=(128, 128, 128))
background = Image.open(backgroundImg).resize((w, h))
render_objects_spatial(background, imgA, relation, args, image_id, annotations)
os.makedirs(os.path.join(args.exp, path), exist_ok=True)
img_file_full = os.path.join(args.exp, img_file)
background.save(img_file_full)
img_info = {}
img_info["license"] = 0
img_info["file_name"] = img_file
img_info["width"] = w
img_info["height"] = h
img_info["id"] = image_id
return img_info, annotations
def gen_syn_data(args):
'''Creates list of objects and distrctor objects to be pasted on what images.
Spawns worker processes and generates images according to given params
Args:
img_files(list): List of image files
labels(list): List of labels for each image
'''
w = args.width
h = args.height
img_list = get_list_of_images(args.root)
labels = get_labels(img_list)
unique_labels = sorted(set(labels))
print ("Number of classes : %d" % len(unique_labels))
print ("Number of images : %d" % len(img_list))
img_files = list(zip(img_list, labels))
N = int(max(np.ceil(args.max_objects*args.total_num/len(img_files)), 1))
print("Objects will be used %d times" % N)
if(args.one_type_per_image):
img_by_labels = {}
img_labels = []
for l in unique_labels:
img_by_labels[l] = []
img_labels.append([])
if not os.path.exists(os.path.join(args.exp, l)):
os.makedirs(os.path.join(args.exp, l))
for img_file in img_files:
img_by_labels[img_file[1]].append(img_file)
for j, key in enumerate(img_by_labels.keys()):
for i in range(N):
img_labels[j] = img_labels[j] + random.sample(img_by_labels[key], len(img_by_labels[key]))
else:
img_labels = []
for i in range(N):
img_labels = img_labels + random.sample(img_files, len(img_files))
background_files = glob.glob(os.path.join(args.background_dir, '*/*.jpg'))
if (not background_files):
background_files = glob.glob(os.path.join(args.background_dir, '*/*/*.jpg'))
print ("Number of background images : %d" % len(background_files))
if (args.add_distractors or args.add_backgroud_distractors):
distractor_list = get_list_of_images(args.distractor_dir)
distractor_labels = get_labels(distractor_list)
distractor_files = list(zip(distractor_list, distractor_labels))
print ("Number of distractor images : %d" % len(distractor_files))
else:
distractor_files = []
idx = 0
img_files = []
anno_files = []
params_list = []
while any(img_labels):
# Get list of objects
objects = []
if (args.stats):
n = int(np.round(max(np.random.lognormal(args.stats["n"]["mean"], args.stats["n"]["std"]), 0), 1))
else:
n = min(random.randint(args.min_objects, args.max_objects), len(img_labels))
if (args.one_type_per_image):
non_empty = [i for i in range(len(img_labels)) if len(img_labels[i])>0]
nn = random.randint(0, len(non_empty)-1)
nl = non_empty[nn]
for i in range(n):
objects.append(img_labels[nl].pop())
else:
for i in range(n):
objects.append(img_labels.pop())
# Get list of distractor objects
distractor_objects = []
if (args.add_distractors or args.add_backgroud_distractors):
n = min(random.randint(args.min_distractor_objects, args.max_distractor_objects), len(distractor_files))
for i in range(n):
distractor_objects.append(random.choice(distractor_files))
#print ("Chosen distractor objects: %s" % distractor_objects)
bg_file = random.choice(background_files)
for blur in args.blending_list:
img_file = '%i_%s-%s.jpg'%(idx,blur, os.path.splitext(os.path.basename(bg_file))[0])
params = (objects, distractor_objects, img_file, bg_file, idx)
params_list.append(params)
img_files.append(img_file)
idx += 1
if (idx >= args.total_num):
break
if (args.workers>1):
partial_func = partial(create_image_anno_wrapper, args=args)
p = get_context("spawn").Pool(args.workers, init_worker)
try:
results = p.map(partial_func, params_list)
except KeyboardInterrupt:
print ("....\nCaught KeyboardInterrupt, terminating workers")
p.terminate()
else:
p.close()
p.join()
else:
results = []
for object in params_list:
img_info, annotations = create_image_anno(*object, args=args)
results.append([img_info, annotations])
return results, unique_labels
def get_article(a, color=None):
if (color):
return ("a " + color + " " + a)
else:
if (a[0] in ("a", "e", "i", "o", "u")):
return "an " + a
else:
return "a " + a
def get_relation(relation):
if (relation in ("left", "right")):
return " to the " + relation + " of "
else:
return " " + relation + " "
def mirror_relation(relation):
if (relation == "left"):
return "right"
elif (relation == "right"):
return "left"
elif (relation == "above"):
return "below"
else:
return "above"
def create_prompts(a, b, relation, background, colorA=None, colorB=None):
background = background.replace("-", " ").replace("_", " ")
prompta = get_article(a, colorA) + get_relation(relation) + get_article(b, colorB) + " in a " + background
promptb = get_article(b, colorB) + get_relation(mirror_relation(relation)) + get_article(a, colorA) + " in a " + background
prompts = [prompta, promptb]
return prompts
def create_prompt(a, relation, background):
background = background.replace("-", " ").replace("_", " ")
prompta = get_article(a) + " on the " + relation + " in a " + background
return prompta
def gen_syn_data_spatial_pairs(args):
'''Creates list of objects and distrctor objects to be pasted on what images.
Spawns worker processes and generates images according to given params
Args:
img_files(list): List of image files
labels(list): List of labels for each image
'''
w = args.width
h = args.height
img_list = get_list_of_images(args.root)
# if (args.val):
# with open(os.path.join(args.root, "val.txt")) as f:
# img_list = f.readlines()
# else:
# with open(os.path.join(args.root, "train.txt")) as f:
# img_list = f.readlines()
img_list = [os.path.join(args.root, b.strip()) for b in img_list]
labels = get_labels(img_list)
unique_labels = sorted(set(labels))
# background_list = get_list_of_images(args.background_dir)
if (args.val):
with open(args.background_dir + "val.txt") as f:
background_list = f.readlines()
else:
with open(args.background_dir + "train.txt") as f:
background_list = f.readlines()
background_list = [os.path.join(args.background_dir, b.strip()) for b in background_list]
background_labels = get_labels(background_list)
unique_background_labels = sorted(set(background_labels))
print ("Number of classes : %d" % len(unique_labels))
print ("Number of input images : %d" % len(img_list))
print ("Number of background classes : %d" % len(unique_background_labels))
print ("Number of background images : %d" % len(background_list))
img_files = list(zip(img_list, labels))
background_files = list(zip(background_list, background_labels))
labels_to_images = {}
for label in labels:
labels_to_images[label] = []
for img_file in img_files:
labels_to_images[img_file[1]].append(img_file[0])
background_labels_to_images = {}
for label in background_labels:
background_labels_to_images[label] = []
for img_file in background_files:
background_labels_to_images[img_file[1]].append(img_file[0])
#unique_labels = random.sample(unique_labels,10)
#print ("Using number of classes : %d" % len(unique_labels))
if (args.focus_objs):
unique_labels = args.focus_objs.split(",")
if (args.total_objs>0):
unique_labels = random.sample(unique_labels,args.total_objs)