-
Notifications
You must be signed in to change notification settings - Fork 63
/
dataset-tools.py
697 lines (549 loc) · 23.2 KB
/
dataset-tools.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
import argparse
import numpy as np
import scipy.ndimage as pyimg
import os
import imutils
import cv2
import random
# print(cv2.__version__)
def parse_args():
desc = "Tools to normalize an image dataset"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('--verbose', action='store_true',
help='Print progress to console.')
parser.add_argument('--force_max', action='store_true',
help='Force max size')
parser.add_argument('-i','--input_folder', type=str,
default='./input/',
help='Directory path to the inputs folder. (default: %(default)s)')
parser.add_argument('-o','--output_folder', type=str,
default='./output/',
help='Directory path to the outputs folder. (default: %(default)s)')
parser.add_argument('-p','--process_type', type=str,
default='resize',
help='Process to use. ["resize","square","crop_to_square","canny","canny-pix2pix","crop_square_patch","scale","many_squares","crop","distance"] (default: %(default)s)')
parser.add_argument('--blur_type', type=str,
default='gaussian',
help='Blur process to use. Use with --process_type canny. ["none","gaussian","median"] (default: %(default)s)')
parser.add_argument('--blur_amount', type=int,
default=1,
help='Amount of blur to apply (use odd numbers). Use with --blur_type. (default: %(default)s)')
parser.add_argument('-cmin','--canny_min', type=int,
default=100,
help='Minimum threshold for Canny use. (default: %(default)s)')
parser.add_argument('-cmax','--canny_max', type=int,
default=300,
help='Maximum threshold for Canny use. (default: %(default)s)')
parser.add_argument('--max_size', type=int,
default=1024,
help='Maximum width or height of the output images. (default: %(default)s)')
parser.add_argument('--height', type=int,
default=None,
help='Maximum height of the output image (for use with --process_type crop). (default: %(default)s)')
parser.add_argument('--width', type=int,
default=None,
help='Maximum width of output image (for use with --process_type crop). (default: %(default)s)')
parser.add_argument('--shift_y', type=int,
default=0,
help='y coordinate shift (for use with --process_type crop). (default: %(default)s)')
parser.add_argument('--v_align', type=str,
default='center',
help='-vertical alignment options: top, bottom, center (for use with --process_type crop_to_square). (default: %(default)s)')
parser.add_argument('--h_align', type=str,
default='center',
help='-vertical alignment options: left, right, center (for use with --process_type crop_to_square). (default: %(default)s)')
parser.add_argument('--shift_x', type=int,
default=0,
help='x coordinate shift (for use with --process_type crop). (default: %(default)s)')
parser.add_argument('--scale', type=float,
default=2.0,
help='Scalar value. For use with scale process type (default: %(default)s)')
parser.add_argument('--skip_tags', type=str,
default=None,
help='comma separated color tags (for Mac only) (default: %(default)s)')
parser.add_argument('--direction', type=str,
default='AtoB',
help='Paired Direction. For use with pix2pix process. ["AtoB","BtoA"] (default: %(default)s)')
parser.add_argument('--border_type', type=str,
default='stretch',
help='Border style to use when using the square process type ["stretch","reflect","solid","inpaint"] (default: %(default)s)')
parser.add_argument('--border_color', type=str,
default='255,255,255',
help='border color to use with the `solid` border type; use bgr values (default: %(default)s)')
# parser.add_argument('--blur_size', type=int,
# default=3,
# help='Blur size. For use with "canny" process. (default: %(default)s)')
parser.add_argument('--mirror', action='store_true',
help='Adds mirror augmentation.')
parser.add_argument('--rotate', action='store_true',
help='Adds 90 degree rotation augmentation.')
parser.add_argument('-f','--file_extension', type=str,
default='png',
help='Border style to use when using the square process type ["png","jpg"] (default: %(default)s)')
feature_parser = parser.add_mutually_exclusive_group(required=False)
feature_parser.add_argument('--keep_name', dest='name', action='store_true')
feature_parser.add_argument('--numbered', dest='name', action='store_false')
parser.set_defaults(name=True)
args = parser.parse_args()
return args
def image_resize(image, width = None, height = None, max = None):
# initialize the dimensions of the image to be resized and
# grab the image size
dim = None
(h, w) = image.shape[:2]
if max is not None:
if w > h:
# produce
r = max / float(w)
dim = (max, int(h * r))
elif h > w:
r = max / float(h)
dim = (int(w * r), max)
else :
dim = (max, max)
else:
# if both the width and height are None, then return the
# original image
if width is None and height is None:
return image
# check to see if the width is None
if width is None:
# calculate the ratio of the height and construct the
# dimensions
r = height / float(h)
dim = (int(w * r), height)
# otherwise, the height is None
else:
# calculate the ratio of the width and construct the
# dimensions
r = width / float(w)
dim = (width, int(h * r))
# resize the image
resized = cv2.resize(image, dim, interpolation = inter)
# return the resized image
return resized
def saveImage(img,path,filename):
if(args.file_extension == "png"):
new_file = os.path.splitext(filename)[0] + ".png"
cv2.imwrite(os.path.join(path, new_file), img, [cv2.IMWRITE_PNG_COMPRESSION, 0])
elif(args.file_extension == "jpg"):
new_file = os.path.splitext(filename)[0] + ".jpg"
cv2.imwrite(os.path.join(path, new_file), img, [cv2.IMWRITE_JPEG_QUALITY, 90])
def image_scale(image, scalar = 1.0):
(h, w) = image.shape[:2]
dim = (int(w*scalar),int(h*scalar))
# resize the image
resized = cv2.resize(image, dim, interpolation = inter)
# return the resized image
return resized
def arbitrary_crop(img, h_crop,w_crop):
error = False
bType = cv2.BORDER_REPLICATE
if(args.border_type == 'solid'):
bType = cv2.BORDER_CONSTANT
elif (args.border_type == 'reflect'):
bType = cv2.BORDER_REFLECT
(h, w) = img.shape[:2]
if(h>h_crop):
hdiff = int((h-h_crop)/2) + args.shift_y
if( ((hdiff+h_crop) > h) or (hdiff < 0)):
print("error! crop settings are too much for this image")
error = True
else:
img = img[hdiff:hdiff+h_crop,0:w]
if(w>w_crop):
wdiff = int((w-w_crop)/2) + args.shift_x
if( ((wdiff+w_crop) > w) or (wdiff < 0) ):
print("error! crop settings are too much for this image")
error = True
else:
img = img[0:h_crop,wdiff:wdiff+w_crop]
return img, error
def crop_to_square(img):
(h, w) = img.shape[:2]
cropped = img.copy()
if w > h:
if (args.h_align=='left'):
print('here first')
cropped = img[:h,:h]
elif (args.h_align=='right'):
cropped = img[0:h, w-h:w]
else:
diff = int((w-h)/2)
cropped = img[0:h, diff:diff+h]
elif h > w:
if (args.v_align=='top'):
cropped = img[:w, :w]
elif (args.v_align=='bottom'):
cropped = img[h-w:h, 0:w]
else:
diff = int((h-w)/2)
cropped = img[diff:diff+w, 0:w]
return cropped
def crop_square_patch(img, imgSize):
(h, w) = img.shape[:2]
rH = random.randint(0,h-imgSize)
rW = random.randint(0,w-imgSize)
cropped = img[rH:rH+imgSize,rW:rW+imgSize]
return cropped
def processCanny(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
if(args.blur_type=='gaussian'):
gray = cv2.GaussianBlur(gray, (args.blur_amount, args.blur_amount), 0)
elif(args.blur_type=='median'):
gray = cv2.medianBlur(gray,args.blur_amount)
gray = cv2.Canny(gray,args.canny_min,args.canny_max)
return gray
def makeResize(img,filename,scale):
remakePath = args.output_folder + str(scale)+"/"
if not os.path.exists(remakePath):
os.makedirs(remakePath)
img_copy = img.copy()
if(args.height!=None and args.width!=None):
img_copy = cv2.resize(img_copy, (args.width,args.height), interpolation = inter)
else:
img_copy = image_resize(img_copy, max = scale)
saveImage(img_copy,remakePath,filename)
if (args.mirror): flipImage(img_copy,filename,remakePath)
if (args.rotate): rotateImage(img_copy,filename,remakePath)
def makeDistance(img,filename,scale):
makePath = args.output_folder + "distance-"+ str(args.max_size)+"/"
if not os.path.exists(makePath):
os.makedirs(makePath)
img_copy = img.copy()
img_copy = image_resize(img_copy, max = scale)
BW = img_copy[:,:,0] > 127
G_channel = pyimg.distance_transform_edt(BW)
G_channel[G_channel>32]=32
B_channel = pyimg.distance_transform_edt(1-BW)
B_channel[B_channel>200]=200
img_copy[:,:,1] = G_channel.astype('uint8')
img_copy[:,:,0] = B_channel.astype('uint8')
if(args.file_extension == "png"):
new_file = os.path.splitext(filename)[0] + ".png"
cv2.imwrite(os.path.join(makePath, new_file), img_copy, [cv2.IMWRITE_PNG_COMPRESSION, 0])
elif(args.file_extension == "jpg"):
new_file = os.path.splitext(filename)[0] + ".jpg"
cv2.imwrite(os.path.join(makePath, new_file), img_copy, [cv2.IMWRITE_JPEG_QUALITY, 90])
if (args.mirror): flipImage(img_copy,new_file,makePath)
if (args.rotate): rotateImage(img_copy,new_file,makePath)
# def makeResizePad(img,filename,scale):
# remakePath = args.output_folder + str(scale)+"/"
# if not os.path.exists(remakePath):
# os.makedirs(remakePath)
# img_copy = img.copy()
# bType = cv2.BORDER_REPLICATE
# if(args.border_type == 'solid'):
# bType = cv2.BORDER_CONSTANT
# elif (args.border_type == 'reflect'):
# bType = cv2.BORDER_REFLECT
# (h, w) = img_copy.shape[:2]
# if(h < scale):
# if(args.file_extension == "png"):
# new_file = os.path.splitext(filename)[0] + ".png"
# cv2.imwrite(os.path.join(remakePath, new_file), img_copy, [cv2.IMWRITE_PNG_COMPRESSION, 0])
# elif(args.file_extension == "jpg"):
# new_file = os.path.splitext(filename)[0] + ".jpg"
# cv2.imwrite(os.path.join(remakePath, new_file), img_copy, [cv2.IMWRITE_JPEG_QUALITY, 90])
# if (args.mirror): flipImage(img_copy,new_file,remakePath)
# if (args.rotate): rotateImage(img_copy,new_file,remakePath)
def makeScale(img,filename,scale):
remakePath = args.output_folder + "scale_"+str(scale)+"/"
if not os.path.exists(remakePath):
os.makedirs(remakePath)
img_copy = img.copy()
img_copy = image_scale(img_copy, scale)
new_file = os.path.splitext(filename)[0] + ".png"
cv2.imwrite(os.path.join(remakePath, new_file), img_copy, [cv2.IMWRITE_PNG_COMPRESSION, 0])
if (args.mirror): flipImage(img_copy,new_file,remakePath)
if (args.rotate): rotateImage(img_copy,new_file,remakePath)
# https://docs.opencv.org/4.5.2/df/d3d/tutorial_py_inpainting.html
def inpaintSquare(img,scale):
print(scale)
(h, w) = img.shape[:2]
mask = np.zeros((h,w,1), np.uint8)
diff_x = scale - w
diff_y = scale - h
if(diff_x%2 == 0 and diff_y%2 == 0 ):
print('1')
img = cv2.copyMakeBorder(img, int(diff_y/2), int(diff_y/2), int(diff_x/2), int(diff_x/2), cv2.BORDER_CONSTANT,value=[255,255,255])
mask = cv2.copyMakeBorder(mask, int(diff_y/2), int(diff_y/2), int(diff_x/2), int(diff_x/2), cv2.BORDER_CONSTANT,value=[255,255,255])
elif(diff_x%2 == 0):
print('2')
img = cv2.copyMakeBorder(img, int(diff_y/2)+1, int(diff_y/2), int(diff_x/2), int(diff_x/2), cv2.BORDER_CONSTANT,value=[255,255,255])
mask = cv2.copyMakeBorder(mask, int(diff_y/2)+1, int(diff_y/2), int(diff_x/2), int(diff_x/2), cv2.BORDER_CONSTANT,value=[255,255,255])
else:
print('3')
img = cv2.copyMakeBorder(img, int(diff_y/2), int(diff_y/2), int(diff_x/2)+1, int(diff_x/2), cv2.BORDER_CONSTANT,value=[255,255,255])
mask = cv2.copyMakeBorder(mask, int(diff_y/2), int(diff_y/2), int(diff_x/2)+1, int(diff_x/2), cv2.BORDER_CONSTANT,value=[255,255,255])
print(img.shape)
print(mask.shape)
return cv2.inpaint(img,mask,3,cv2.INPAINT_NS)
def makeSquare(img,filename,scale):
sqPath = args.output_folder + "sq-"+str(scale)+"/"
if not os.path.exists(sqPath):
os.makedirs(sqPath)
img_sq = img.copy()
(h, w) = img_sq.shape[:2]
if((h < scale) and (w < scale)):
if(args.verbose): print('skip resize')
else:
img_sq = image_resize(img_sq, max = scale)
if(args.border_type=="inpaint"):
img_sq = inpaintSquare(img_sq, scale)
else:
bType = cv2.BORDER_REPLICATE
if(args.border_type == 'solid'):
bType = cv2.BORDER_CONSTANT
elif (args.border_type == 'reflect'):
bType = cv2.BORDER_REFLECT
bColor = [int(item) for item in args.border_color.split(',')]
(h, w) = img_sq.shape[:2]
if(args.force_max):
diff_x = scale - w
diff_y = scale - h
if(diff_x%2 == 0 and diff_y%2 == 0 ):
img_sq = cv2.copyMakeBorder(img_sq, int(diff_y/2), int(diff_y/2), int(diff_x/2), int(diff_x/2), bType,value=bColor)
elif(diff_x%2 == 0):
img_sq = cv2.copyMakeBorder(img_sq, int(diff_y/2)+1, int(diff_y/2), int(diff_x/2), int(diff_x/2), bType,value=bColor)
elif(diff_y%2 == 0):
img_sq = cv2.copyMakeBorder(img_sq, int(diff_y/2), int(diff_y/2), int(diff_x/2)+1, int(diff_x/2), bType,value=bColor)
#checks if our division leads to incorrect image sizes
elif ((h + (int(diff_y/2)*2) != scale) or (w + (int(diff_x/2)*2) != scale)):
if(h + (int(diff_y/2)*2) != scale) and (w + (int(diff_x/2)*2) != scale):
img_sq = cv2.copyMakeBorder(img_sq, int(diff_y/2)+1, int(diff_y/2), int(diff_x/2)+1, int(diff_x/2), bType,value=bColor)
elif(h + (int(diff_y/2)*2) != scale):
img_sq = cv2.copyMakeBorder(img_sq, int(diff_y/2), int(diff_y/2), int(diff_x/2)+1, int(diff_x/2), bType,value=bColor)
elif(w + (int(diff_x/2)*2) != scale):
img_sq = cv2.copyMakeBorder(img_sq, int(diff_y/2)+1, int(diff_y/2), int(diff_x/2), int(diff_x/2), bType,value=bColor)
else:
img_sq = cv2.copyMakeBorder(img_sq, int(diff_y/2), int(diff_y/2), int(diff_x/2)+1, int(diff_x/2), bType,value=bColor)
elif(h > w):
# pad left/right
diff = h-w
if(diff%2 == 0):
img_sq = cv2.copyMakeBorder(img_sq, 0, 0, int(diff/2), int(diff/2), bType,value=bColor)
else:
img_sq = cv2.copyMakeBorder(img_sq, 0, 0, int(diff/2)+1, int(diff/2), bType,value=bColor)
elif(w > h):
# pad top/bottom
diff = w-h
if(args.v_align == 'bottom'):
img_sq = cv2.copyMakeBorder(img_sq, diff, 0, 0, 0, bType,value=bColor)
else:
if(diff%2 == 0):
img_sq = cv2.copyMakeBorder(img_sq, int(diff/2), int(diff/2), 0, 0, bType,value=bColor)
else:
img_sq = cv2.copyMakeBorder(img_sq, int(diff/2), int(diff/2)+1, 0, 0, bType,value=bColor)
else:
diff = scale-h
if(diff%2 == 0):
img_sq = cv2.copyMakeBorder(img_sq, int(diff/2), int(diff/2), int(diff/2), int(diff/2), bType,value=bColor)
else:
img_sq = cv2.copyMakeBorder(img_sq, int(diff/2), int(diff/2)+1, int(diff/2), int(diff/2)+1, bType,value=bColor)
if(args.file_extension == "png"):
new_file = os.path.splitext(filename)[0] + ".png"
cv2.imwrite(os.path.join(sqPath, new_file), img_sq, [cv2.IMWRITE_PNG_COMPRESSION, 0])
elif(args.file_extension == "jpg"):
new_file = os.path.splitext(filename)[0] + ".jpg"
cv2.imwrite(os.path.join(sqPath, new_file), img_sq, [cv2.IMWRITE_JPEG_QUALITY, 90])
if (args.mirror): flipImage(img_sq,new_file,sqPath)
if (args.rotate): rotateImage(img_sq,new_file,sqPath)
def makeCanny(img,filename,scale):
make_path = args.output_folder + "canny-"+str(scale)+"/"
if not os.path.exists(make_path):
os.makedirs(make_path)
img_copy = img.copy()
img_copy = image_resize(img_copy, max = scale)
gray = processCanny(img_copy)
# save out
if(args.file_extension == "png"):
new_file = os.path.splitext(filename)[0] + ".png"
cv2.imwrite(os.path.join(make_path, new_file), gray, [cv2.IMWRITE_PNG_COMPRESSION, 0])
elif(args.file_extension == "jpg"):
new_file = os.path.splitext(filename)[0] + ".jpg"
cv2.imwrite(os.path.join(make_path, new_file), gray, [cv2.IMWRITE_JPEG_QUALITY, 90])
if (args.mirror): flipImage(img_copy,new_file,make_path)
if (args.rotate): rotateImage(img_copy,new_file,make_path)
def makeCrop(img,filename):
make_path = args.output_folder + "crop-"+str(args.height)+"x"+str(args.width)+"/"
if not os.path.exists(make_path):
os.makedirs(make_path)
img_copy = img.copy()
img_copy,error = arbitrary_crop(img_copy,args.height,args.width)
if((img_copy.shape[0] != args.height) or (img_copy.shape[1] != args.width)):
# print(img_copy.shape[1], args.height, img_copy.shape[0], args.width)
print("unable to crop to the size requested")
if (error==False):
if(args.file_extension == "png"):
new_file = os.path.splitext(filename)[0] + ".png"
cv2.imwrite(os.path.join(make_path, new_file), img_copy, [cv2.IMWRITE_PNG_COMPRESSION, 0])
elif(args.file_extension == "jpg"):
new_file = os.path.splitext(filename)[0] + ".jpg"
cv2.imwrite(os.path.join(make_path, new_file), img_copy, [cv2.IMWRITE_JPEG_QUALITY, 90])
if (args.mirror): flipImage(img_copy,new_file,make_path)
if (args.rotate): rotateImage(img_copy,new_file,make_path)
else:
if(args.verbose): print(filename+" returned an error")
def makeSquareCrop(img,filename,scale):
make_path = args.output_folder + "sq-"+str(scale)+"/"
if not os.path.exists(make_path):
os.makedirs(make_path)
img_copy = img.copy()
img_copy = crop_to_square(img_copy)
img_copy = image_resize(img_copy, max = scale)
if(args.file_extension == "png"):
new_file = os.path.splitext(filename)[0] + ".png"
cv2.imwrite(os.path.join(make_path, new_file), img_copy, [cv2.IMWRITE_PNG_COMPRESSION, 0])
elif(args.file_extension == "jpg"):
new_file = os.path.splitext(filename)[0] + ".jpg"
cv2.imwrite(os.path.join(make_path, new_file), img_copy, [cv2.IMWRITE_JPEG_QUALITY, 90])
if (args.mirror): flipImage(img_copy,new_file,make_path)
if (args.rotate): rotateImage(img_copy,new_file,make_path)
def makeManySquares(img,filename,scale):
make_path = args.output_folder + "many_squares-"+str(scale)+"/"
if not os.path.exists(make_path):
os.makedirs(make_path)
img_copy = img.copy()
(h, w) = img_copy.shape[:2]
img_ratio = h/w
if(img_ratio >= 1.2):
#crop images from top and bottom
crop = img_copy[0:w,0:w]
crop = image_resize(crop, max = scale)
saveImage(crop,make_path,filename+"-1")
if (args.mirror): flipImage(crop,filename+"-1",make_path)
if (args.rotate): rotateImage(crop,filename+"-1",make_path)
crop = img_copy[h-w:h,0:w]
crop = image_resize(crop, max = scale)
saveImage(crop,make_path,filename+"-2")
if (args.mirror): flipImage(crop,filename+"-2",make_path)
if (args.rotate): rotateImage(crop,filename+"-2",make_path)
elif(img_ratio <= .8):
#crop images from left and right
print(os.path.splitext(filename)[0] + ': wide image')
crop = img_copy[0:h,0:h]
crop = image_resize(crop, max = scale)
saveImage(crop,make_path,filename+"-1")
if (args.mirror): flipImage(crop,filename+"-1",make_path)
if (args.rotate): rotateImage(crop,filename+"-1",make_path)
crop = img_copy[0:h,w-h:w]
crop = image_resize(crop, max = scale)
saveImage(crop,make_path,filename+"-2")
if (args.mirror): flipImage(crop,filename+"-2",make_path)
if (args.rotate): rotateImage(crop,filename+"-2",make_path)
else:
img_copy = crop_to_square(img_copy)
img_copy = image_resize(img_copy, max = scale)
saveImage(img_copy,make_path,filename)
if(args.mirror): flipImage(img_copy,filename,make_path)
if(args.rotate): rotateImage(img_copy,filename,make_path)
def makeSquareCropPatch(img,filename,scale):
make_path = args.output_folder + "sq-"+str(scale)+"/"
if not os.path.exists(make_path):
os.makedirs(make_path)
img_copy = img.copy()
img_copy = crop_square_patch(img_copy,args.max_size)
new_file = os.path.splitext(filename)[0] + ".png"
cv2.imwrite(os.path.join(make_path, new_file), img_copy, [cv2.IMWRITE_PNG_COMPRESSION, 0])
if (args.mirror): flipImage(img_copy,new_file,make_path)
if (args.rotate): rotateImage(img_copy,new_file,make_path)
def makePix2Pix(img,filename,scale,direction="BtoA",value=[0,0,0]):
img_p2p = img.copy()
img_p2p = image_resize(img_p2p, max = scale)
(h, w) = img_p2p.shape[:2]
bType = cv2.BORDER_CONSTANT
make_path = args.output_folder + "pix2pix-"+str(h)+"/"
if not os.path.exists(make_path):
os.makedirs(make_path)
canny = cv2.cvtColor(processCanny(img_p2p),cv2.COLOR_GRAY2RGB)
if(direction=="BtoA"):
img_p2p = cv2.copyMakeBorder(img_p2p, 0, 0, w, 0, bType, None, value)
img_p2p[0:h,0:w] = canny
if(args.file_extension == "png"):
new_file = os.path.splitext(filename)[0] + ".png"
cv2.imwrite(os.path.join(make_path, new_file), img_p2p, [cv2.IMWRITE_PNG_COMPRESSION, 0])
elif(args.file_extension == "jpg"):
new_file = os.path.splitext(filename)[0] + ".jpg"
cv2.imwrite(os.path.join(make_path, new_file), img_p2p, [cv2.IMWRITE_JPEG_QUALITY, 90])
def flipImage(img,filename,path):
flip_img = cv2.flip(img, 1)
flip_file = os.path.splitext(filename)[0] + "-flipped"
saveImage(flip_img,path,flip_file)
def rotateImage(img,filename,path):
r = img.copy()
r = imutils.rotate_bound(r, 90)
saveImage(r,path,filename+"-rot90")
r = imutils.rotate_bound(r, 90)
saveImage(r,path,filename+"-rot180")
r = imutils.rotate_bound(r, 90)
saveImage(r,path,filename+"-rot270")
def processImage(img,filename):
if args.process_type == "resize":
makeResize(img,filename,args.max_size)
if args.process_type == "resize_pad":
makeResizePad(img,filename,args.max_size)
if args.process_type == "square":
makeSquare(img,filename,args.max_size)
if args.process_type == "crop_to_square":
makeSquareCrop(img,filename,args.max_size)
if args.process_type == "canny":
makeCanny(img,filename,args.max_size)
if args.process_type == "canny-pix2pix":
makePix2Pix(img,filename,args.max_size)
if args.process_type == "crop_square_patch":
makeSquareCropPatch(img,filename,args.max_size)
if args.process_type == "scale":
makeScale(img,filename,args.scale)
if args.process_type == "many_squares":
makeManySquares(img,filename,args.max_size)
if args.process_type == "crop":
makeCrop(img,filename)
if args.process_type == "distance":
makeDistance(img,filename,args.max_size)
def main():
global args
global count
global inter
args = parse_args()
count = int(0)
inter = cv2.INTER_CUBIC
os.environ['OPENCV_IO_ENABLE_JASPER']= "true"
if(args.skip_tags != None):
import mac_tag
if os.path.isdir(args.input_folder):
print("Processing folder: " + args.input_folder)
elif os.path.isfile(args.input_folder):
img = cv2.imread(args.input_folder)
filename = args.input_folder.split('/')[-1]
if hasattr(img, 'copy'):
if(args.verbose): print('processing image: ' + filename)
processImage(img,os.path.splitext(filename)[0])
for root, subdirs, files in os.walk(args.input_folder):
if(args.verbose): print('--\nroot = ' + root)
for subdir in subdirs:
if(args.verbose): print('\t- subdirectory ' + subdir)
for filename in files:
skipped = False
file_path = os.path.join(root, filename)
if(args.verbose): print('\t- file %s (full path: %s)' % (filename, file_path))
if(args.skip_tags != None):
tags = [str(item) for item in args.skip_tags.split(',')]
# tags = mac_tag.get(file_path)
# print(tags)
for tag in tags:
matches = mac_tag.match(tag,file_path)
if(file_path in matches):
print('skipping file: ' + filename)
skipped = True
if not skipped:
img = cv2.imread(file_path)
if hasattr(img, 'copy'):
if(args.verbose): print('processing image: ' + filename)
if args.name:
processImage(img,os.path.splitext(filename)[0])
else:
processImage(img,str(count))
count = count + int(1)
if __name__ == "__main__":
main()