-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMisc.py
4669 lines (4200 loc) · 154 KB
/
Misc.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
__author__ = 'Tommy'
import os
import sys
import re
import shutil
try:
from PIL import Image, ImageChops
except ImportError as e:
print('PIL import failed: {}'.format(e))
try:
import cv2
except ImportError as e:
print('OpenCV import failed: {}'.format(e))
try:
import matplotlib
from matplotlib import pyplot as plt
from matplotlib import font_manager as ftm
# from matplotlib.mlab import PCA
from matplotlib import animation
from mpl_toolkits.mplot3d import Axes3D
except ImportError as e:
print('matplotlib import failed: {}'.format(e))
import copy
import struct
import time
from tqdm import tqdm
# from DecompUtils import getBinaryPtsImage2
from Homography import *
# import six
col_rgb = {
'snow': (250, 250, 255),
'snow_2': (233, 233, 238),
'snow_3': (201, 201, 205),
'snow_4': (137, 137, 139),
'ghost_white': (255, 248, 248),
'white_smoke': (245, 245, 245),
'gainsboro': (220, 220, 220),
'floral_white': (240, 250, 255),
'old_lace': (230, 245, 253),
'linen': (230, 240, 240),
'antique_white': (215, 235, 250),
'antique_white_2': (204, 223, 238),
'antique_white_3': (176, 192, 205),
'antique_white_4': (120, 131, 139),
'papaya_whip': (213, 239, 255),
'blanched_almond': (205, 235, 255),
'bisque': (196, 228, 255),
'bisque_2': (183, 213, 238),
'bisque_3': (158, 183, 205),
'bisque_4': (107, 125, 139),
'peach_puff': (185, 218, 255),
'peach_puff_2': (173, 203, 238),
'peach_puff_3': (149, 175, 205),
'peach_puff_4': (101, 119, 139),
'navajo_white': (173, 222, 255),
'moccasin': (181, 228, 255),
'cornsilk': (220, 248, 255),
'cornsilk_2': (205, 232, 238),
'cornsilk_3': (177, 200, 205),
'cornsilk_4': (120, 136, 139),
'ivory': (240, 255, 255),
'ivory_2': (224, 238, 238),
'ivory_3': (193, 205, 205),
'ivory_4': (131, 139, 139),
'lemon_chiffon': (205, 250, 255),
'seashell': (238, 245, 255),
'seashell_2': (222, 229, 238),
'seashell_3': (191, 197, 205),
'seashell_4': (130, 134, 139),
'honeydew': (240, 255, 240),
'honeydew_2': (224, 238, 244),
'honeydew_3': (193, 205, 193),
'honeydew_4': (131, 139, 131),
'mint_cream': (250, 255, 245),
'azure': (255, 255, 240),
'alice_blue': (255, 248, 240),
'lavender': (250, 230, 230),
'lavender_blush': (245, 240, 255),
'misty_rose': (225, 228, 255),
'white': (255, 255, 255),
'black': (0, 0, 0),
'dark_slate_gray': (79, 79, 49),
'dim_gray': (105, 105, 105),
'slate_gray': (144, 138, 112),
'light_slate_gray': (153, 136, 119),
'gray': (190, 190, 190),
'light_gray': (211, 211, 211),
'midnight_blue': (112, 25, 25),
'navy': (128, 0, 0),
'cornflower_blue': (237, 149, 100),
'dark_slate_blue': (139, 61, 72),
'slate_blue': (205, 90, 106),
'medium_slate_blue': (238, 104, 123),
'light_slate_blue': (255, 112, 132),
'medium_blue': (205, 0, 0),
'royal_blue': (225, 105, 65),
'blue': (255, 0, 0),
'dodger_blue': (255, 144, 30),
'deep_sky_blue': (255, 191, 0),
'sky_blue': (250, 206, 135),
'light_sky_blue': (250, 206, 135),
'steel_blue': (180, 130, 70),
'light_steel_blue': (222, 196, 176),
'light_blue': (230, 216, 173),
'powder_blue': (230, 224, 176),
'pale_turquoise': (238, 238, 175),
'dark_turquoise': (209, 206, 0),
'medium_turquoise': (204, 209, 72),
'turquoise': (208, 224, 64),
'cyan': (255, 255, 0),
'light_cyan': (255, 255, 224),
'cadet_blue': (160, 158, 95),
'medium_aquamarine': (170, 205, 102),
'aquamarine': (212, 255, 127),
'dark_green': (0, 100, 0),
'dark_olive_green': (47, 107, 85),
'dark_sea_green': (143, 188, 143),
'sea_green': (87, 139, 46),
'medium_sea_green': (113, 179, 60),
'light_sea_green': (170, 178, 32),
'pale_green': (152, 251, 152),
'spring_green': (127, 255, 0),
'lawn_green': (0, 252, 124),
'chartreuse': (0, 255, 127),
'medium_spring_green': (154, 250, 0),
'green_yellow': (47, 255, 173),
'lime_green': (50, 205, 50),
'yellow_green': (50, 205, 154),
'forest_green': (34, 139, 34),
'olive_drab': (35, 142, 107),
'dark_khaki': (107, 183, 189),
'khaki': (140, 230, 240),
'pale_goldenrod': (170, 232, 238),
'light_goldenrod_yellow': (210, 250, 250),
'light_yellow': (224, 255, 255),
'yellow': (0, 255, 255),
'gold': (0, 215, 255),
'light_goldenrod': (130, 221, 238),
'goldenrod': (32, 165, 218),
'dark_goldenrod': (11, 134, 184),
'rosy_brown': (143, 143, 188),
'indian_red': (92, 92, 205),
'saddle_brown': (19, 69, 139),
'sienna': (45, 82, 160),
'peru': (63, 133, 205),
'burlywood': (135, 184, 222),
'beige': (220, 245, 245),
'wheat': (179, 222, 245),
'sandy_brown': (96, 164, 244),
'tan': (140, 180, 210),
'chocolate': (30, 105, 210),
'firebrick': (34, 34, 178),
'brown': (42, 42, 165),
'dark_salmon': (122, 150, 233),
'salmon': (114, 128, 250),
'light_salmon': (122, 160, 255),
'orange': (0, 165, 255),
'dark_orange': (0, 140, 255),
'coral': (80, 127, 255),
'light_coral': (128, 128, 240),
'tomato': (71, 99, 255),
'orange_red': (0, 69, 255),
'red': (0, 0, 255),
'hot_pink': (180, 105, 255),
'deep_pink': (147, 20, 255),
'pink': (203, 192, 255),
'light_pink': (193, 182, 255),
'pale_violet_red': (147, 112, 219),
'maroon': (96, 48, 176),
'medium_violet_red': (133, 21, 199),
'violet_red': (144, 32, 208),
'violet': (238, 130, 238),
'plum': (221, 160, 221),
'orchid': (214, 112, 218),
'medium_orchid': (211, 85, 186),
'dark_orchid': (204, 50, 153),
'dark_violet': (211, 0, 148),
'blue_violet': (226, 43, 138),
'purple': (240, 32, 160),
'medium_purple': (219, 112, 147),
'thistle': (216, 191, 216),
'green': (0, 255, 0),
'magenta': (255, 0, 255)
}
def getBinaryPtsImage2(img_shape, corners):
img_shape = img_shape[0:2]
corners = corners.transpose().astype(np.int32)
# print 'corners:\n ', corners
bin_img = np.zeros(img_shape, dtype=np.uint8)
cv2.fillConvexPoly(bin_img, corners, (255, 255, 255))
# drawRegion(bin_img, corners, (255, 255, 255), thickness=1)
# # print 'img_shape: ', img_shape
# min_row = max(0, int(np.amin(corners[1, :])))
# max_row = min(img_shape[0], int(np.amax(corners[1, :])))
# for row in xrange(min_row, max_row):
# non_zero_idx = np.transpose(np.nonzero(bin_img[row, :]))
# # print 'curr_row: ', curr_row
# # print 'non_zero_idx: ', non_zero_idx
# bin_img[row, non_zero_idx[0]:non_zero_idx[-1]] = 255
return bin_img
# def getBinaryPtsImage2(img_shape, corners):
# img_shape = img_shape[0:2]
# bin_img = np.zeros(img_shape, dtype=np.uint8)
# drawRegion(bin_img, corners, (255, 255, 255), thickness=1)
# # print 'img_shape: ', img_shape
# for row in xrange(img_shape[0]):
# non_zero_idx = np.transpose(np.nonzero(bin_img[row, :]))
# # print 'curr_row: ', curr_row
# # print 'non_zero_idx: ', non_zero_idx
# if non_zero_idx.shape[0]>1:
# bin_img[row, non_zero_idx[0]:non_zero_idx[-1]] = 255
# return bin_img
def sortKey(fname, only_basename=1):
if only_basename:
fname = os.path.splitext(os.path.basename(fname))[0]
else:
# remove extension
fname = os.path.join(os.path.dirname(fname),
os.path.splitext(os.path.basename(fname))[0])
fname_list = fname.split(os.sep)
# print('fname_list: ', fname_list)
out_name = ''
for _dir in fname_list:
out_name = '{}_{}'.format(out_name, _dir) if out_name else _dir
# print('zip_path: ', out_name)
fname = out_name
# print('fname: ', fname)
# split_fname = fname.split('_')
# print('split_fname: ', split_fname)
split_list = fname.split('_')
key = ''
for s in split_list:
if s.isdigit():
if not key:
key = '{:012d}'.format(int(s))
else:
key = '{}-{:012d}'.format(key, int(s))
else:
try:
nums = [int(k) for k in re.findall(r'\d+', s)]
# print('\ts: {}\t nums: {}\n'.format(s, nums))
for num in nums:
s = s.replace(str(num), '{:012d}'.format(num))
except ValueError:
pass
if not key:
key = s
else:
key = '{}-{}'.format(key, s)
# print('fname: {}\t key: {}\n'.format(fname, key))
return key
def sortKeyOld(fname):
fname = os.path.splitext(fname)[0]
# print('fname: ', fname)
# split_fname = fname.split('_')
# print('split_fname: ', split_fname)
nums = [int(s) for s in fname.split('_') if s.isdigit()]
non_nums = [s for s in fname.split('_') if not s.isdigit()]
key = ''
for non_num in non_nums:
if not key:
key = non_num
else:
key = '{}_{}'.format(key, non_num)
for num in nums:
if not key:
key = '{:08d}'.format(num)
else:
key = '{}_{:08d}'.format(key, num)
# try:
# key = nums[-1]
# except IndexError:
# return fname
# print('key: ', key)
return key
def trim(im, all_corners=0, margin=-5):
im_size = im.size
# print('im_size: {}'.format(im_size))
h, w = im_size[:2]
bg_pix_ul = im.getpixel((0, 0))
bg_pixs = [bg_pix_ul, ]
if all_corners:
bg_pix_ur = im.getpixel((0, w - 1))
bg_pix_ll = im.getpixel((h - 1, 0))
bg_pix_lr = im.getpixel((h - 1, w - 1))
bg_pixs += [bg_pix_ur, bg_pix_ll, bg_pix_lr]
# im.show()
# print('bg_pix: {}'.format(bg_pix))
for pix in bg_pixs:
bg = Image.new(im.mode, im_size, pix)
diff = ImageChops.difference(im, bg)
# diff.show()
diff = ImageChops.add(diff, diff, 2.0, margin)
# diff.show()
# diff = ImageChops.add(diff, diff)
bbox = diff.getbbox()
if bbox:
im = im.crop(bbox)
return im
def move_or_del_files(src_path, filenames, dst_path='', remove_empty=1):
if dst_path:
print('moving files from {} --> {}'.format(src_path, dst_path))
os.makedirs(dst_path, exist_ok=True)
else:
print('deleting files in {}'.format(src_path))
for filename in tqdm(filenames):
file_src_path = os.path.join(src_path, filename)
if not dst_path:
os.remove(file_src_path)
else:
file_dst_path = os.path.join(dst_path, filename)
shutil.move(file_src_path, file_dst_path)
if remove_empty and not os.listdir(src_path):
print('deleting empty folder: {}'.format(src_path))
shutil.rmtree(src_path)
def processArguments(args, params):
# arguments specified as 'arg_name=argv_val'
no_of_args = len(args)
for arg_id in range(no_of_args):
arg_str = args[arg_id]
if arg_str.startswith('--'):
arg_str = arg_str[2:]
arg = arg_str.split('=')[-2:]
if len(arg) == 3:
arg = arg[1:]
# print('args[{}]: {}'.format(arg_id, args[arg_id]))
# print('arg: {}'.format(arg))
if len(arg) != 2 or arg[0] not in params.keys():
raise IOError('Invalid argument provided: {:s}'.format(args[arg_id]))
return
if not arg[1] or not arg[0] or arg[1] == '#':
continue
if isinstance(params[arg[0]], (list, tuple)):
# if not ',' in arg[1]:
# print('Invalid argument provided for list: {:s}'.format(arg[1]))
# return
if arg[1] and ',' not in arg[1]:
arg[1] = '{},'.format(arg[1])
arg_vals = arg[1].split(',')
arg_vals_parsed = []
for _val in arg_vals:
try:
_val_parsed = int(_val)
except ValueError:
try:
_val_parsed = float(_val)
except ValueError:
_val_parsed = _val if _val else None
if _val_parsed == '__n__':
_val_parsed = ''
if _val_parsed is not None:
arg_vals_parsed.append(_val_parsed)
params[arg[0]] = arg_vals_parsed
else:
params[arg[0]] = type(params[arg[0]])(arg[1])
if isinstance(params[arg[0]], str) and params[arg[0]] == '__n__':
params[arg[0]] = ''
def resizeAR(src_img, width=0, height=0, return_factors=False,
placement_type=0, resize_factor=0):
src_height, src_width, n_channels = src_img.shape
src_aspect_ratio = float(src_width) / float(src_height)
if isinstance(placement_type, int):
placement_type = (placement_type, placement_type)
# print('placement_type: {}'.format(placement_type))
# print('placement_type: {}'.format(placement_type))
if resize_factor != 0:
width, height = int(src_width * resize_factor), int(src_height * resize_factor)
if width <= 0 and height <= 0:
if resize_factor == 0:
raise AssertionError(
'Both width and height cannot be 0 when resize_factor is 0 too')
elif height <= 0:
height = int(width / src_aspect_ratio)
elif width <= 0:
width = int(height * src_aspect_ratio)
aspect_ratio = float(width) / float(height)
# print('src_aspect_ratio: {}'.format(src_aspect_ratio))
# print('aspect_ratio: {}'.format(aspect_ratio))
if src_aspect_ratio == aspect_ratio:
dst_width = src_width
dst_height = src_height
start_row = start_col = 0
elif src_aspect_ratio > aspect_ratio:
dst_width = src_width
dst_height = int(src_width / aspect_ratio)
start_row = int((dst_height - src_height) / 2.0)
if placement_type[0] == 0:
start_row = 0
# start_row = int(dst_height - src_height)
elif placement_type[0] == 1:
start_row = int((dst_height - src_height) / 2.0)
elif placement_type[0] == 2:
# start_row = 0
start_row = int(dst_height - src_height)
start_col = 0
else:
dst_height = src_height
dst_width = int(src_height * aspect_ratio)
start_col = int((dst_width - src_width) / 2.0)
if placement_type[1] == 0:
start_col = 0
elif placement_type[1] == 1:
start_col = int((dst_width - src_width) / 2.0)
elif placement_type[1] == 2:
start_col = int(dst_width - src_width)
start_row = 0
dst_img = np.zeros((dst_height, dst_width, n_channels), dtype=np.uint8)
dst_img[start_row:start_row + src_height, start_col:start_col + src_width, :] = src_img
dst_img = cv2.resize(dst_img, (width, height))
if return_factors:
resize_factor = float(height) / float(dst_height)
return dst_img, resize_factor, start_row, start_col
else:
return dst_img
def sizeAR(src_img, height=0, width=0):
src_height, src_width, n_channels = src_img.shape
src_aspect_ratio = float(src_width) / float(src_height)
if width <= 0 and height <= 0:
return src_height, src_width
elif height <= 0:
height = int(width / src_aspect_ratio)
elif width <= 0:
width = int(height * src_aspect_ratio)
return height, width
def str2num(s):
try:
return int(s)
except ValueError:
return float(s)
def print_and_write(_str, fname=None):
sys.stdout.write(_str + '\n')
sys.stdout.flush()
if fname is not None:
open(fname, 'a').write(_str + '\n')
def printMatrixToFile(mat, mat_name, fname, fmt='{:15.9f}', mode='w', sep='\t'):
fid = open(fname, mode)
fid.write('{:s}:\n'.format(mat_name))
for i in range(mat.shape[0]):
for j in range(mat.shape[1]):
fid.write(fmt.format(mat[i, j]) + sep)
fid.write('\n')
fid.write('\n\n')
fid.close()
def printVectorFile(mat, mat_name, fname, fmt='{:15.9f}', mode='w', sep='\t'):
fid = open(fname, mode)
# print 'mat before: ', mat
mat = mat.squeeze()
# mat = mat.squeeze()
# if len(mat.shape) > 1:
# print 'here we are outside'
# mat = mat[0, 0]
#
# print 'mat: ', mat
# print 'mat.size: ', mat.size
# print 'mat.shape: ', mat.shape
fid.write('{:s}:\n'.format(mat_name))
for i in range(mat.size):
val = mat[i]
# print 'type( val ): ', type( val )
# if not isinstance(val, (int, long, float)) or type( val )=='numpy.float64':
# print 'here we are'
# val = mat[0, i]
# print 'val: ', val
fid.write(fmt.format(val) + sep)
fid.write('\n')
fid.write('\n\n')
fid.close()
def printScalarToFile(scalar_val, scalar_name,
fname, fmt='{:15.9f}', mode='w'):
fid = open(fname, mode)
fid.write('{:s}:\t'.format(scalar_name))
fid.write(fmt.format(scalar_val))
fid.write('\n\n')
fid.close()
def getTrackingObject(img, col=(0, 0, 255), title=None):
annotated_img = img.copy()
temp_img = img.copy()
if title is None:
title = 'Select the object to track'
cv2.namedWindow(title)
cv2.imshow(title, annotated_img)
pts = []
def drawLines(img, hover_pt=None):
if len(pts) == 0:
cv2.imshow(title, img)
return
for i in range(len(pts) - 1):
cv2.line(img, pts[i], pts[i + 1], col, 1)
if hover_pt is None:
return
cv2.line(img, pts[-1], hover_pt, col, 1)
if len(pts) == 3:
cv2.line(img, pts[0], hover_pt, col, 1)
elif len(pts) == 4:
return
cv2.imshow(title, img)
def mouseHandler(event, x, y, flags=None, param=None):
if len(pts) >= 4:
return
if event == cv2.EVENT_LBUTTONDOWN:
pts.append((x, y))
temp_img = annotated_img.copy()
drawLines(temp_img)
elif event == cv2.EVENT_LBUTTONUP:
pass
elif event == cv2.EVENT_RBUTTONDOWN:
if len(pts) > 0:
print('Removing last point')
del (pts[-1])
temp_img = annotated_img.copy()
drawLines(temp_img)
elif event == cv2.EVENT_RBUTTONUP:
pass
elif event == cv2.EVENT_MBUTTONDOWN:
pass
elif event == cv2.EVENT_MOUSEMOVE:
# if len(pts) == 0:
# return
temp_img = annotated_img.copy()
drawLines(temp_img, (x, y))
cv2.setMouseCallback(title, mouseHandler, param=[annotated_img, temp_img, pts])
while len(pts) < 4:
key = cv2.waitKey(1)
if key == 27:
break
cv2.waitKey(250)
cv2.destroyWindow(title)
drawLines(annotated_img, pts[0])
return pts, annotated_img
def getTrackingObject2(img, col=(0, 0, 255), title=None, line_thickness=1):
annotated_img = img.copy()
temp_img = img.copy()
if title is None:
title = 'Select the object to track'
cv2.namedWindow(title)
cv2.imshow(title, annotated_img)
pts = []
def drawLines(img, hover_pt=None):
if len(pts) == 0:
cv2.imshow(title, img)
return
for i in range(len(pts) - 1):
cv2.line(img, pts[i], pts[i + 1], col, line_thickness)
if hover_pt is None:
return
cv2.line(img, pts[-1], hover_pt, col, line_thickness)
if len(pts) == 3:
cv2.line(img, pts[0], hover_pt, col, line_thickness)
elif len(pts) == 4:
return
cv2.imshow(title, img)
def mouseHandler(event, x, y, flags=None, param=None):
if len(pts) >= 4:
return
if event == cv2.EVENT_LBUTTONDOWN:
pts.append((x, y))
temp_img = annotated_img.copy()
drawLines(temp_img)
elif event == cv2.EVENT_LBUTTONUP:
pass
elif event == cv2.EVENT_RBUTTONDOWN:
if len(pts) > 0:
print('Removing last point')
del (pts[-1])
temp_img = annotated_img.copy()
drawLines(temp_img)
elif event == cv2.EVENT_RBUTTONUP:
pass
elif event == cv2.EVENT_MBUTTONDOWN:
pass
elif event == cv2.EVENT_MOUSEMOVE:
# if len(pts) == 0:
# return
temp_img = annotated_img.copy()
drawLines(temp_img, (x, y))
cv2.setMouseCallback(title, mouseHandler, param=[annotated_img, temp_img, pts])
while len(pts) < 4:
key = cv2.waitKey(1)
if key == 27:
sys.exit()
cv2.waitKey(250)
cv2.destroyWindow(title)
drawLines(annotated_img, pts[0])
return pts
def readTrackingData(filename, arch_fid=None):
if arch_fid is not None:
data_file = arch_fid.open(filename, 'r')
else:
if not os.path.isfile(filename):
print("Tracking data file not found:\n ", filename)
return None
data_file = open(filename, 'r')
data_file.readline()
lines = data_file.readlines()
data_file.close()
no_of_lines = len(lines)
data_array = np.empty([no_of_lines, 8])
line_id = 0
for line in lines:
# print(line)
words = line.split()
coordinates = []
if len(words) != 9:
if len(words) == 2 and words[1] == 'invalid_tracker_state':
for i in range(8):
coordinates.append(float('NaN'))
else:
msg = "Invalid formatting on line %d" % line_id + " in file %s" % filename + ":\n%s" % line
raise SyntaxError(msg)
else:
words = words[1:]
for word in words:
coordinates.append(float(word))
data_array[line_id, :] = coordinates
# print words
line_id += 1
return data_array
def getFileList(root_dir, ext):
file_list = []
for file in os.listdir(root_dir):
if file.endswith(ext):
file_list.append(os.path.join(root_dir, file))
return file_list
def readTrackingDataMOT(filename, arch_fid=None):
if arch_fid is not None:
data_file = arch_fid.open(filename, 'r')
else:
if not os.path.isfile(filename):
print("Tracking data file not found:\n ", filename)
return None
data_file = open(filename, 'r')
lines = data_file.readlines()
data_file.close()
no_of_lines = len(lines)
data_array = np.empty([no_of_lines, 10])
line_id = 0
n_frames = 0
for line in lines:
# print(line)
words = line.split(',')
data = []
if len(words) != 10:
if len(words) == 7:
for i in range(3):
words.append('-1')
else:
msg = "Invalid formatting on line %d" % line_id + " in file %s" % filename + ":\n%s" % line
raise SyntaxError(msg)
for word in words:
data.append(float(word))
data_array[line_id, :] = data
# print words
line_id += 1
return data_array
# new version that supports reinit data as well as invalid tracker states
def readTrackingData2(tracker_path, n_frames, _arch_fid=None, _reinit_from_gt=0):
print('Reading tracking data from: {:s}...'.format(tracker_path))
if _arch_fid is not None:
tracking_data = _arch_fid.open(tracker_path, 'r').readlines()
else:
tracking_data = open(tracker_path, 'r').readlines()
if len(tracking_data) < 2:
print('Tracking data file is invalid.')
return None, None
# remove the header
del (tracking_data[0])
n_lines = len(tracking_data)
if not _reinit_from_gt and n_lines != n_frames:
print("No. of frames in tracking result ({:d}) and the ground truth ({:d}) do not match".format(
n_lines, n_frames))
return None
line_id = 1
failure_count = 0
invalid_tracker_state_found = False
data_array = []
while line_id < n_lines:
tracking_data_line = tracking_data[line_id].strip().split()
frame_fname = str(tracking_data_line[0])
fname_len = len(frame_fname)
frame_fname_1 = frame_fname[0:5]
frame_fname_2 = frame_fname[- 4:]
if frame_fname_1 != 'frame' or frame_fname_2 != '.jpg':
print('Invaid formatting on tracking data line {:d}: {:s}'.format(line_id + 1, tracking_data_line))
print('frame_fname: {:s} fname_len: {:d} frame_fname_1: {:s} frame_fname_2: {:s}'.format(
frame_fname, fname_len, frame_fname_1, frame_fname_2))
return None, None
frame_id_str = frame_fname[5:-4]
frame_num = int(frame_id_str)
if len(tracking_data_line) != 9:
if _reinit_from_gt and len(tracking_data_line) == 2 and tracking_data_line[1] == 'tracker_failed':
print('tracking failure detected in frame: {:d} at line {:d}'.format(frame_num, line_id + 1))
failure_count += 1
data_array.append('tracker_failed')
line_id += 2
continue
elif len(tracking_data_line) == 2 and tracking_data_line[1] == 'invalid_tracker_state':
if not invalid_tracker_state_found:
print('invalid tracker state detected in frame: {:d} at line {:d}'.format(frame_num, line_id + 1))
invalid_tracker_state_found = True
line_id += 1
data_array.append('invalid_tracker_state')
continue
else:
print('Invalid formatting on line {:d}: {:s}'.format(line_id, tracking_data[line_id]))
return None, None
data_array.append([float(tracking_data_line[1]), float(tracking_data_line[2]),
float(tracking_data_line[3]), float(tracking_data_line[4]),
float(tracking_data_line[5]), float(tracking_data_line[6]),
float(tracking_data_line[7]), float(tracking_data_line[8])])
return data_array, failure_count
def readWarpData(filename):
if not os.path.isfile(filename):
print("Warp data file not found:\n ", filename)
sys.exit()
data_file = open(filename, 'r')
lines = data_file.readlines()
lines = (line.rstrip() for line in lines)
lines = list(line for line in lines if line)
data_file.close()
no_of_lines = len(lines)
warps_array = np.zeros((no_of_lines, 9), dtype=np.float64)
line_id = 0
for line in lines:
words = line.split()
if len(words) != 9:
msg = "Invalid formatting on line %d" % line_id + " in file %s" % filename + ":\n%s" % line
raise SyntaxError(msg)
curr_warp = []
for word in words:
curr_warp.append(float(word))
warps_array[line_id, :] = curr_warp
line_id += 1
return warps_array
def getNormalizedUnitSquarePts(resx=100, resy=100, c=1.0):
pts_arr = np.mat(np.zeros((2, resy * resx)))
pt_id = 0
for y in np.linspace(-c, c, resy):
for x in np.linspace(-c, c, resx):
pts_arr[0, pt_id] = x
pts_arr[1, pt_id] = y
pt_id += 1
corners = np.mat([[-c, c, c, -c], [-c, -c, c, c]])
return pts_arr, corners
def drawRegion(img, corners, color, thickness=1, annotate_corners=False,
annotation_col=(0, 255, 0), annotation_font_size=1):
n_pts = corners.shape[1]
for i in range(n_pts):
p1 = (int(corners[0, i]), int(corners[1, i]))
p2 = (int(corners[0, (i + 1) % n_pts]), int(corners[1, (i + 1) % n_pts]))
if cv2.__version__.startswith('21'):
cv2.line(img, p1, p2, color, thickness, cv2.CV_AA)
else:
cv2.line(img, p1, p2, color, thickness, cv2.LINE_AA)
if annotate_corners:
if annotation_col is None:
annotation_col = color
cv2.putText(img, '{:d}'.format(i + 1), p1, cv2.FONT_HERSHEY_COMPLEX_SMALL,
annotation_font_size, annotation_col)
def getPixValsRGB(pts, img):
try:
n_channels = img.shape[2]
except IndexError:
n_channels = 1
# print 'img: ', img
n_pts = pts.shape[1]
pix_vals = np.zeros((n_pts, n_channels), dtype=np.float64)
for channel_id in range(n_channels):
try:
curr_channel = img[:, :, channel_id].astype(np.float64)
except IndexError:
curr_channel = img
pix_vals[:, channel_id] = getPixVals(pts, curr_channel)
return pix_vals
def getPixVals(pts, img):
x = pts[0, :]
y = pts[1, :]
n_rows, n_cols = img.shape
x[x < 0] = 0
y[y < 0] = 0
x[x > n_cols - 1] = n_cols - 1
y[y > n_rows - 1] = n_rows - 1
lx = np.floor(x).astype(np.uint16)
ux = np.ceil(x).astype(np.uint16)
ly = np.floor(y).astype(np.uint16)
uy = np.ceil(y).astype(np.uint16)
dx = x - lx
dy = y - ly
ll = np.multiply((1 - dx), (1 - dy))
lu = np.multiply(dx, (1 - dy))
ul = np.multiply((1 - dx), dy)
uu = np.multiply(dx, dy)
# n_rows, n_cols = img.shape
# lx[lx < 0] = 0
# lx[lx >= n_cols] = n_cols - 1
# ux[ux < 0] = 0
# ly[ly < 0] = 0
# ly[ly >= n_rows] = n_rows - 1
# uy[uy < 0] = 0
# ux[ux >= n_cols] = n_cols - 1
# uy[uy >= n_rows] = n_rows - 1
return np.multiply(img[ly, lx], ll) + np.multiply(img[ly, ux], lu) + \
np.multiply(img[uy, lx], ul) + np.multiply(img[uy, ux], uu)
def drawGrid(img, pts, res_x, res_y, color, thickness=1):
# draw vertical lines
for x_id in range(res_x):
for y_id in range(res_y - 1):
pt_id1 = y_id * res_x + x_id
pt_id2 = (y_id + 1) * res_x + x_id
p1 = (int(pts[0, pt_id1]), int(pts[1, pt_id1]))
p2 = (int(pts[0, pt_id2]), int(pts[1, pt_id2]))
cv2.line(img, p1, p2, color, thickness, cv2.LINE_AA)
# draw horizontal lines
for y_id in range(res_y):
for x_id in range(res_x - 1):
pt_id1 = y_id * res_x + x_id
pt_id2 = y_id * res_x + x_id + 1
p1 = (int(pts[0, pt_id1]), int(pts[1, pt_id1]))
p2 = (int(pts[0, pt_id2]), int(pts[1, pt_id2]))
cv2.line(img, p1, p2, color, thickness)
def draw_dotted_line(img, pt1, pt2, color, thickness=1, gap=7):
dist = ((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2) ** .5
pts = []
for i in np.arange(0, dist, gap):
r = i / dist
x = int((pt1[0] * (1 - r) + pt2[0] * r) + .5)
y = int((pt1[1] * (1 - r) + pt2[1] * r) + .5)
p = (x, y)
pts.append(p)
# if style == 'dotted':
for p in pts:
cv2.circle(img, p, thickness, color, -1)
# else:
# s = pts[0]
# e = pts[0]
# i = 0
# for p in pts:
# s = e
# e = p
# if i % 2 == 1:
# cv2.line(img, s, e, color, thickness)
# i += 1
def imshow(titles, frames, _pause):
if isinstance(titles, str):
titles = (titles,)
frames = (frames,)
for title, frame in zip(titles, frames):
cv2.imshow(title, frame)
if _pause > 1:
wait = _pause
else:
wait = 1 - _pause
k = cv2.waitKey(wait)
if k == 27:
sys.exit()
elif k == 32:
_pause = 1 - _pause
return _pause, k
def draw_dotted_poly(img, pts, color, thickness=1):
s = pts[0]
e = pts[0]
pts.append(pts.pop(0))
for p in pts:
s = e
e = p
draw_dotted_line(img, s, e, color, thickness)
def draw_dotted_rect(img, pt1, pt2, color, thickness=1):
pts = [pt1, (pt2[0], pt1[1]), pt2, (pt1[0], pt2[1])]
draw_dotted_poly(img, pts, color, thickness)
def drawBox(image, xmin, ymin, xmax, ymax,
box_color=(0, 255, 0), label=None, thickness=2, is_dotted=False):
# if cv2.__version__.startswith('3'):
# font_line_type = cv2.LINE_AA