-
Notifications
You must be signed in to change notification settings - Fork 0
/
Social_grouping.py
1705 lines (1563 loc) · 76.7 KB
/
Social_grouping.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
from __future__ import print_function
import math
import os
import cv2
import copy
import pickle
import numpy as np
#from sets import Set
from scipy.spatial import ConvexHull
from scipy.stats import norm
from scipy.stats import truncnorm
from sklearn.cluster import DBSCAN
from PIL import Image
class SocialGrouping(object):
# This class imports data from eth and ucy datasets
# The data are stored in two formats:
# ---If using people centered format: (indices are matched)
# ------people_start_frame: record the start frame of each person
# ------ when the person first makes its appearance
# ------ (people_start_frame[i] means the start frame of ith person)
# ------people_end_frame: record the end frame of each person
# ------ when the person last makes its appearance
# ------ (people_end_frame[i] means the end frame of ith person)
# ------people_coords_complete: the coordinates of each person throughout its appearance
# ------ (people_coords_complete[i][j][0] means the x coordinate
# ------ of person i in frame j+people_start_frame[i])
# ------people_velocity_complete: the coordinates of each person throughout its appearance
# ------ (people_velocity_complete[i][j][0] means the x velocity
# ------ of person i in frame j+people_start_frame[i])
# ---If using frame centered format: (indices are matched)
# ------video_position_matrix: A 3D irregular list
# ------ 1st Dimension indicates frames
# ------ 2nd Dimension indicates people
# ------ 3rd Dimension indicates coordinates of each person
# ------ (video_position_matrix[i][j][0] means the x coordinate
# ------ of preson j in frame i)
# ------video_velocity_matrix: A 3D irregular list
# ------ 1st Dimension indicates frames
# ------ 2nd Dimension indicates people
# ------ 3rd Dimension indicates velocities of each person
# ------ (video_velocity_matrix[i][j][0] means the x velocity
# ------ of preson j in frame i)
#
# Note: eth data are in meters form
def __init__(self, dataset = 'eth', flag = 0):
self._init_transform_params()
self.dataset = dataset
self.flag = flag
self.video_position_matrix = []
self.video_velocity_matrix = []
self.video_pedidx_matrix = []
self.video_labels_matrix = []
self.video_debug_labels_matrix = []
self.video_dynamics_matrix = []
self.people_start_frame = []
self.people_end_frame = []
self.people_coords_complete = []
self.people_velocity_complete = []
self.frame_id_list = []
self.person_id_list = []
self.x_list = []
self.y_list = []
self.vx_list = []
self.vy_list = []
self.H = []
self.action_frames = []
self.num_groups = 0
self.train_ratio = 0.9
if dataset == 'eth':
read_success = self._read_eth_data(flag)
elif dataset == 'ucy':
read_success = self._read_ucy_data(flag)
else:
print('dataset argument must be \'eth\' or \'ucy\'')
read_success = False
if read_success:
self._organize_frame()
#self._data_normalization()
self._data_processing()
self._load_parameters(dataset)
self._social_grouping()
#self._refine_split_merge()
self.num_merge = 0
self.num_split = 0
for action_info in self.video_dynamics_matrix:
self.action_frames.append(action_info[1])
action = action_info[0]
if action == 1:
self.num_merge += 1
else:
self.num_split += 1
self.num_merge_train = int(self.num_merge * self.train_ratio)
self.num_merge_test = self.num_merge - self.num_merge_train
self.num_split_train = int(self.num_split * self.train_ratio)
self.num_split_test = self.num_split - self.num_split_train
self.merge_category_array = np.array([0] * self.num_merge_train + \
[1] * self.num_merge_test)
self.split_category_array = np.array([0] * self.num_split_train + \
[1] * self.num_split_test)
np.random.shuffle(self.merge_category_array)
np.random.shuffle(self.split_category_array)
self.num_groups += 1
return
def _init_transform_params(self):
self.frame_width = 0
self.frame_height = 0
self.H = 0
self.aug_trans = 0
self.aug_angle = 0
self.bbox_crop = 0
self.process_scale = 0
self.new_size = 0
return
def _read_eth_data(self, flag):
if flag == 0:
folder = 'seq_eth'
elif flag == 1:
folder = 'seq_hotel'
else:
print('Flag for \'eth\' should be 0 or 1')
return False
# Create a VideoCapture object and get total number of frames
self.fname = 'ewap_dataset/' + folder + '/' + folder + '.avi'
cap = cv2.VideoCapture(self.fname)
if (cap.isOpened()== False):
print("Error opening video stream or file")
self.total_num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
self.frame_width = int(cap.get(3))
self.frame_height = int(cap.get(4))
cap.release()
self.has_video = True
# Read Homography matrix
fname = 'ewap_dataset/' + folder + '/H.txt'
with open(fname) as f:
for line in f:
line = line.split(' ')
real_line = []
for elem in line:
if len(elem) > 0:
real_line.append(elem)
real_line[-1] = real_line[-1][:-1]
h1, h2, h3 = real_line
self.H.append([float(h1), float(h2), float(h3)])
f.close()
# Read the data from text file
fname = 'ewap_dataset/'+ folder + '/obsmat.txt'
with open(fname) as f:
for line in f:
line = line.split(' ')
real_line = []
for elem in line:
if len(elem) > 0:
real_line.append(elem)
real_line[-1] = real_line[-1]
frame_id, person_id, x, z, y, vx, vz, vy = real_line
self.frame_id_list.append(int(round(float(frame_id))))
self.person_id_list.append(int(round(float(person_id))))
x = float(x)
y = float(y)
vx = float(vx)
vy = float(vy)
# pt = np.matmul(np.linalg.inv(self.H), [[x], [y], [1.0]])
# x, y = (pt[0] / pt[2]), (pt[1] / pt[2])
# pt = np.matmul(np.linalg.inv(self.H), [[vx], [vy], [1.0]])
# vx, vy = (pt[0] / pt[2]), (pt[1] / pt[2])
self.x_list.append(x)
self.y_list.append(y)
self.vx_list.append(vx)
self.vy_list.append(vy)
f.close()
#curr_std = np.std(np.linalg.norm(np.array([self.vx_list, self.vy_list]), axis = 0))
#for i in range(len(self.vx_list)):
# self.vx_list[i] = self.vx_list[i] / curr_std
# self.vx_list[i] = self.vx_list[i] / curr_std
print('File reading done!')
return True
def _read_ucy_data(self, flag):
if flag == 0:
folder = 'zara'
source = 'crowds_zara01'
elif flag == 1:
folder = 'zara'
source = 'crowds_zara02'
elif flag == 2:
folder = 'university_students'
source = 'students003'
elif flag == 3:
folder = 'zara'
source = 'crowds_zara03'
elif flag == 4:
folder = 'university_students'
source = 'students001'
elif flag == 5:
folder = 'arxiepiskopi'
source = 'arxiepiskopi1'
print('Warning: bad data used!')
else:
print('Flag for \'ucy\' should be 0 - 5')
return False
# Create a VideoCapture object and read from input file
if (flag == 3) or (flag == 4):
if flag == 3:
alt_source = 'crowds_zara01'
else:
alt_source = 'students003'
self.fname = 'ucy_dataset/' + folder + '/' + alt_source + '.avi'
cap = cv2.VideoCapture(self.fname)
if (cap.isOpened()== False):
print("Error opening video stream or file")
self.total_num_frames = -1
self.has_video = False
else:
self.fname = 'ucy_dataset/' + folder + '/' + source + '.avi'
cap = cv2.VideoCapture(self.fname)
if (cap.isOpened()== False):
print("Error opening video stream or file")
self.total_num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
self.has_video = True
self.frame_width = int(cap.get(3))
self.frame_height = int(cap.get(4))
cap.release()
# Approximate H matrix
offx = 17.5949
offy = 9.665722
pts_img = np.array([[476, 117], [562, 117], [562, 311],[476, 311]])
pts_wrd = np.array([[0, 0], [1.81, 0], [1.81, 4.63],[0, 4.63]])
pts_wrd[:,0] += offx
pts_wrd[:,1] += offy
self.H, status = cv2.findHomography(pts_img, pts_wrd)
# Read the data from text file
fname = 'ucy_dataset/' + folder + '/data_' + folder + '/' + source + '.vsp'
with open(fname) as f:
person_id = 0
mem_x = 0
mem_y = 0
mem_frame_id = 0
record_switch = True
for idx, line in enumerate(f):
line = line.split()
if len(line) == 6:
person_id += 1
record_switch = False
if idx > 0:
vx = self.vx_list[-1]
vy = self.vy_list[-1]
self.vx_list.append(vx)
self.vy_list.append(vy)
if (len(line) == 8) or (len(line) == 4):
x = float(line[0])
y = float(line[1])
frame_id = int(line[2])
pt = np.matmul(self.H, [[x], [y], [1.0]]) # H
x, y = (pt[0][0] / pt[2][0]), (pt[1][0] / pt[2][0])
self.x_list.append(x)
self.y_list.append(y)
self.frame_id_list.append(frame_id)
self.person_id_list.append(person_id)
if record_switch:
vx = (x - mem_x) / (frame_id - mem_frame_id)
vy = (y - mem_y) / (frame_id - mem_frame_id)
self.vx_list.append(vx * 25)
self.vy_list.append(vy * 25)
else:
record_switch = True
mem_x = x
mem_y = y
mem_frame_id = frame_id
vx = self.vx_list[-1]
vy = self.vy_list[-1]
self.vx_list.append(vx)
self.vy_list.append(vy)
f.close()
#curr_std = np.std(np.linalg.norm(np.array([self.vx_list, self.vy_list]), axis = 0))
#for i in range(len(self.vx_list)):
# self.vx_list[i] = self.vx_list[i] / curr_std
# self.vx_list[i] = self.vx_list[i] / curr_std
print('File reading done!')
return True
def _organize_frame(self):
# Connect paths for each individual person
# For each person, the frame ids, the associated path
# coordinates and velocities are stored
num_people = max(self.person_id_list)
for i in range(num_people):
got_start = False
prev_frame = 0
curr_frame = 0
person_coords = []
person_velocity = []
mem_x = 0
mem_y = 0
mem_vel_x = 0
mem_vel_y = 0
for j in range(len(self.frame_id_list)):
if self.person_id_list[j] == (i + 1):
curr_frame = self.frame_id_list[j]
if not got_start:
got_start = True
self.people_start_frame.append(curr_frame)
person_coords.append((self.x_list[j], self.y_list[j]))
person_velocity.append((self.vx_list[j], self.vy_list[j]))
else:
num_frames_interpolated = curr_frame - prev_frame
for k in range(num_frames_interpolated):
ratio = float(k + 1) / float(num_frames_interpolated)
diff_x = ratio * (self.x_list[j] - mem_x)
diff_y = ratio * (self.y_list[j] - mem_y)
person_coords.append((mem_x + diff_x, mem_y + diff_y))
diff_vx = ratio * (self.vx_list[j] - mem_vel_x)
diff_vy = ratio * (self.vy_list[j] - mem_vel_y)
person_velocity.append((mem_vel_x + diff_vx, mem_vel_y + diff_vy))
mem_x, mem_y = self.x_list[j], self.y_list[j]
mem_vel_x, mem_vel_y = self.vx_list[j], self.vy_list[j]
prev_frame = curr_frame
if got_start:
self.people_end_frame.append(curr_frame)
self.people_coords_complete.append(person_coords)
self.people_velocity_complete.append(person_velocity)
if self.total_num_frames == -1:
self.total_num_frames = max(self.people_end_frame)
print('Frame organizing done!')
return
def _data_normalization(self, xy_separate = False):
all_coords_x = []
all_coords_y = []
all_velocity_x = []
all_velocity_y = []
all_coords = []
all_velocity = []
for i in range(len(self.people_coords_complete)):
for j in range(len(self.people_coords_complete[i])):
all_coords_x.append(self.people_coords_complete[i][j][0])
all_coords_y.append(self.people_coords_complete[i][j][1])
all_coords.append(self.people_coords_complete[i][j][0])
all_coords.append(self.people_coords_complete[i][j][1])
all_velocity_x.append(self.people_velocity_complete[i][j][0])
all_velocity_y.append(self.people_velocity_complete[i][j][1])
all_velocity.append(self.people_velocity_complete[i][j][0])
all_velocity.append(self.people_velocity_complete[i][j][1])
self.coords_x_mean = np.mean(np.array(all_coords_x))
self.coords_y_mean = np.mean(np.array(all_coords_y))
self.coords_x_std = np.std(np.array(all_coords_x))
self.coords_y_std = np.std(np.array(all_coords_y))
self.coords_mean = np.mean(np.array(all_coords))
self.coords_std = np.std(np.array(all_coords))
self.velocity_x_mean = np.mean(np.array(all_velocity_x))
self.velocity_y_mean = np.mean(np.array(all_velocity_y))
self.velocity_x_std = np.std(np.array(all_velocity_x))
self.velocity_y_std = np.std(np.array(all_velocity_y))
self.velocity_mean = np.mean(np.array(all_velocity))
self.velocity_std = np.std(np.array(all_velocity))
for i in range(len(self.people_coords_complete)):
for j in range(len(self.people_coords_complete[i])):
if xy_separate:
new_coord_x = (self.people_coords_complete[i][j][0] - self.coords_x_mean) / \
self.coords_x_std
new_coord_y = (self.people_coords_complete[i][j][1] - self.coords_y_mean) / \
self.coords_y_std
new_vel_x = (self.people_velocity_complete[i][j][0] - self.velocity_x_mean) / \
self.velocity_x_std
new_vel_y = (self.people_velocity_complete[i][j][1] - self.velocity_y_mean) / \
self.velocity_y_std
else:
new_coord_x = (self.people_coords_complete[i][j][0] - self.coords_mean) / \
self.coords_std
new_coord_y = (self.people_coords_complete[i][j][1] - self.coords_mean) / \
self.coords_std
new_vel_x = (self.people_velocity_complete[i][j][0] - self.velocity_mean) / \
self.velocity_std
new_vel_y = (self.people_velocity_complete[i][j][1] - self.velocity_mean) / \
self.velocity_std
self.people_coords_complete[i][j] = (new_coord_x, new_coord_y)
self.people_velocity_complete[i][j] = (new_vel_x, new_vel_y)
return
def _data_processing(self):
# Precompute a 3d video array for displaying later
# Frames x Clusters x Entities
# Clustering is done using DBScan
for i in range(self.total_num_frames):
position_array = []
velocity_array = []
pedidx_array = []
curr_frame = i + 1
for j in range(len(self.people_start_frame)):
curr_start = self.people_start_frame[j]
curr_end = self.people_end_frame[j]
if (curr_start <= curr_frame) and (curr_frame <= curr_end):
x, y = self.people_coords_complete[j][curr_frame - curr_start]
vx, vy = self.people_velocity_complete[j][curr_frame - curr_start]
#computes and gets the coords in pixels instead of meters (NOT YET)
position_array.append((float(x), float(y)))
velocity_array.append((float(vx), float(vy)))
pedidx_array.append(j)
if len(position_array) > 0:
self.video_position_matrix.append(position_array)
self.video_velocity_matrix.append(velocity_array)
self.video_pedidx_matrix.append(pedidx_array)
else:
self.video_position_matrix.append([])
self.video_velocity_matrix.append([])
self.video_pedidx_matrix.append([])
print('Initial data processing done!')
return
def _load_parameters(self, dataset):
offset = 12
history = offset + 16
seq_length = 16
future = 0
interval = 2
self.ucy_scale = 1 #60
pos = 2.0
ori = 30
vel = 1.0
if dataset == 'eth':
self.param = {'position_threshold': pos,
'orientation_threshold': ori / 180.0 * math.pi,
'velocity_threshold': vel,
'temporal_threshold': 0.3,
'velocity_ignore_threshold': 0.5,
'label_history_threshold': history,
'label_future_threshold': future,
'label_history_offset': offset,
'label_history_seqlength': seq_length,
'label_history_interval': interval}
elif dataset == 'ucy':
self.param = {'position_threshold': pos * self.ucy_scale,
'orientation_threshold': ori / 180.0 * math.pi,
'velocity_threshold': vel * self.ucy_scale, #16.5,
'temporal_threshold': 0.3 * self.ucy_scale,
'velocity_ignore_threshold': 0.5 * self.ucy_scale,
'label_history_threshold': history,
'label_future_threshold': future,
'label_history_offset': offset,
'label_history_seqlength': seq_length,
'label_history_interval': interval}
else:
raise Exception('Non existant dataset!')
return
def _DBScan_grouping(self, labels, properties, standard):
max_lb = max(labels)
for lb in range(max_lb + 1):
sub_properties = []
sub_idxes = []
for i in range(len(labels)):
if labels[i] == lb:
sub_properties.append(properties[i])
sub_idxes.append(i)
if len(sub_idxes) > 1:
db = DBSCAN(eps = standard, min_samples = 1)
sub_labels = db.fit_predict(sub_properties)
max_label = max(labels)
for i, sub_lb in enumerate(sub_labels):
if sub_lb > 0:
labels[sub_idxes[i]] = max_label + sub_lb
return labels
def _check_history(self, label, frame_idx):
history = self.param['label_history_threshold']
if frame_idx < history:
return False
for i in range(frame_idx - history, frame_idx):
if not (label in self.video_labels_matrix[i]):
return False
return True
def _check_future(self, label, frame_idx):
future = self.param['label_future_threshold']
if frame_idx > (self.total_num_frames - future):
end_idx = self.total_num_frames
else:
end_idx = frame_idx + future
for i in range(frame_idx, end_idx):
if not (label in self.video_labels_matrix[i]):
return False
return True
def _social_grouping(self):
prev_labels = []
prev_pedidx = []
for i in range(self.total_num_frames):
# get grouping criterion
position_array = self.video_position_matrix[i]
velocity_array = self.video_velocity_matrix[i]
pedidx_array = self.video_pedidx_matrix[i]
num_people = len(position_array)
if not (num_people > 0):
prev_labels = []
prev_pedidx = []
self.video_labels_matrix.append([])
self.video_debug_labels_matrix.append([])
continue
vel_orientation_array = []
vel_magnitude_array = []
for [vx, vy] in velocity_array:
velocity_magnitude = math.sqrt(math.pow(vx, 2) + math.pow(vy, 2))
if velocity_magnitude < self.param['velocity_ignore_threshold']:
vel_orientation_array.append((0.0, 0.0))
vel_magnitude_array.append((0.0, 0.0))
else:
vel_orientation_array.append(
(vx / velocity_magnitude, vy / velocity_magnitude))
vel_magnitude_array.append(
(0.0, velocity_magnitude)) # Add 0 to fool DBSCAN
# grouping in current frame
labels = [0] * num_people
labels = self._DBScan_grouping(labels, vel_orientation_array,
self.param['orientation_threshold'])
labels = self._DBScan_grouping(labels, vel_magnitude_array,
self.param['velocity_threshold'])
labels = self._DBScan_grouping(labels, position_array,
self.param['position_threshold'])
# Fixes to ensure temporal consistency (cross frame comparison)
if i == 0:
temporal_labels = copy.deepcopy(labels)
else:
temporal_labels = [-1] * num_people
# Get the temporal labels (labeled w.r.t. a close label in last frame)
for j in range(num_people):
curr_idx = pedidx_array[j]
for k in range(len(prev_labels)):
if prev_pedidx[k] == curr_idx:
temporal_labels[j] = prev_labels[k]
"""
curr_label = labels[j]
curr_pos = position_array[j]
distances = [0] * len(prev_labels)
min_dist = 100000
for k in range(len(prev_labels)):
target_pos = prev_positions[k]
distances[k] = math.sqrt(math.pow(curr_pos[0] - target_pos[0], 2) +
math.pow(curr_pos[1] - target_pos[1], 2))
if distances[k] < min_dist:
min_dist = distances[k]
min_idx = k
if min_dist < self.param['temporal_threshold']:
temporal_labels[j] = prev_labels[min_idx]
"""
# Figure out new groups
for j in range(num_people):
curr_label = temporal_labels[j]
reference_label = labels[j]
# new group or join current group
if curr_label == -1:
found_group = False
for k in range(num_people):
if (labels[k] == reference_label) and (temporal_labels[k] != -1):
change_to_label = temporal_labels[k]
found_group = True
if not found_group:
change_to_label = max(self.num_groups, max(temporal_labels)) + 1
for k in range(j, num_people):
if labels[k] == reference_label:
temporal_labels[k] = change_to_label
# resolve splits and merges
dynamics_array = []
for j in range(num_people):
curr_label = temporal_labels[j]
reference_label = labels[j]
for k in range(num_people):
if (temporal_labels[k] != curr_label) and \
(labels[k] == reference_label): #merges
change_to_label = max(self.num_groups, max(temporal_labels)) + 1
if (self._check_history(temporal_labels[k], i)) and \
(self._check_history(curr_label, i)):
dynamics_array.append((1, curr_label, temporal_labels[k], j))
for l in range(num_people):
if labels[l] == reference_label:
temporal_labels[l] = change_to_label
if (temporal_labels[k] == curr_label) and \
(labels[k] != reference_label): #splits
change_to_label_1 = max(self.num_groups, max(temporal_labels)) + 1
change_to_label_2 = max(self.num_groups, max(temporal_labels)) + 2
if self._check_history(curr_label, i):
dynamics_array.append((-1, curr_label, j, k))
for l in range(num_people):
if (labels[l] == labels[k]):
temporal_labels[l] = change_to_label_1
if (labels[l] == reference_label):
temporal_labels[l] = change_to_label_2
"""
dynamics_array = []
for j in range(num_people):
curr_label = temporal_labels[j]
reference_label = labels[j]
for k in range(num_people):
if (temporal_labels[k] == curr_label) and \
(labels[k] != reference_label): #splits
change_to_label_1 = max(temporal_labels) + 1
change_to_label_2 = max(temporal_labels) + 2
if self._check_history(curr_label, i):
dynamics_array.append((-1, curr_label, j, k))
for l in range(num_people):
if (labels[l] == labels[k]):
temporal_labels[l] = change_to_label_1
if (labels[l] == reference_label):
temporal_labels[l] = change_to_label_2
# resolve merges
for j in range(num_people):
curr_label = temporal_labels[j]
reference_label = labels[j]
for k in range(num_people):
if (temporal_labels[k] != curr_label) and \
(labels[k] == reference_label): #merges
change_to_label = max(temporal_labels) + 1
if (self._check_history(temporal_labels[k], i)) and \
(self._check_history(curr_label, i)):
dynamics_array.append((1, curr_label, temporal_labels[k], j))
for l in range(num_people):
if labels[l] == reference_label:
temporal_labels[l] = change_to_label
"""
for info in dynamics_array:
if info[0] == -1:
self.video_dynamics_matrix.append((-1, i, info[1],
temporal_labels[info[2]], temporal_labels[info[3]]))
elif info[0] == 1:
self.video_dynamics_matrix.append((1, i, info[1], info[2],
temporal_labels[info[3]]))
prev_labels = temporal_labels
prev_pedidx = pedidx_array
self.num_groups = max(self.num_groups, max(temporal_labels))
self.video_labels_matrix.append(temporal_labels)
self.video_debug_labels_matrix.append(labels)
print('Social Grouping done!')
return
def _refine_split_merge(self):
new_video_dynamics_matrix = []
for i, action_info in enumerate(self.video_dynamics_matrix):
action = action_info[0]
action_frame = action_info[1]
if action == 1:
after_group_label = action_info[4]
flag1 = self._check_future(after_group_label, action_frame)
flag2 = True
elif action == -1:
after_group_1_label = action_info[3]
after_group_2_label = action_info[4]
flag1 = self._check_future(after_group_1_label, action_frame)
flag2 = self._check_future(after_group_2_label, action_frame)
if flag1 and flag2:
new_video_dynamics_matrix.append(action_info)
self.video_dynamics_matrix = new_video_dynamics_matrix
return
def _draw_social_shapes(self, frame, position, velocity, data_aug, draw = True):
front_coeff = 1.0
side_coeff = 2.0 / 3.0
rear_coeff = 0.5
total_increments = 20
quater_increments = total_increments / 4
angle_increment = 2 * math.pi / total_increments
current_target = 0.8
contour_points = []
for i in range(len(position)):
center_x = position[i][0]
center_y = position[i][1]
velocity_x = velocity[i][0]
velocity_y = velocity[i][1]
velocity_magnitude = math.sqrt(math.pow(velocity_x, 2) + math.pow(velocity_y, 2))
velocity_angle = math.atan2(velocity_y, velocity_x)
if self.dataset == 'eth':
variance_front = max(0.5, front_coeff * velocity_magnitude)
else:
variance_front = max(0.5 * self.ucy_scale, front_coeff * velocity_magnitude) \
* self.ucy_scale
variance_side = side_coeff * variance_front
variance_rear = rear_coeff * variance_front
for j in range(total_increments):
if (j / quater_increments) == 0:
prev_variance = variance_front
next_variance = variance_side
elif (j / quater_increments) == 1:
prev_variance = variance_rear
next_variance = variance_side
elif (j / quater_increments) == 2:
prev_variance = variance_rear
next_variance = variance_side
else:
prev_variance = variance_front
next_variance = variance_side
current_variance = prev_variance + (next_variance - prev_variance) * \
(j % quater_increments) / float(quater_increments)
#value = norm.ppf(current_target, scale = math.sqrt(current_variance))
#value = 0.8416 * math.sqrt(current_variance)
value = math.sqrt(0.354163 / ((math.cos(angle_increment * j) ** 2 / (2 * prev_variance)) + (math.sin(angle_increment * j) ** 2 / (2 * next_variance))))
addition_angle = velocity_angle + angle_increment * j
append_x = center_x + math.cos(addition_angle) * value
append_y = center_y + math.sin(addition_angle) * value
x, y = self._coordinate_transform((append_x, append_y))
contour_points.append((y, x))
convex_hull_vertices = []
hull = ConvexHull(np.array(contour_points))
for i in hull.vertices:
hull_vertice = (contour_points[i][0], contour_points[i][1])
if data_aug:
convex_hull_vertices.append(self._aug_transform(hull_vertice))
else:
convex_hull_vertices.append(hull_vertice)
if draw:
cv2.fillConvexPoly(frame, np.array(convex_hull_vertices), (255, 255, 255))
return frame
else:
return convex_hull_vertices
def _draw_simulated_social_shapes(self, frame, position, data_aug, debug = False):
robo_pos = self.curr_robo_pos
ped_diameter = 0.5
scan_res = 0.1 * math.pi / 180
r_sq = (ped_diameter / 2.0) ** 2
add_noise = True
noise_limit = 0.05
laser_points = []
th = 0
while th < (math.pi * 2):
if not abs(th - math.pi / 2) < 1e-12:
min_dist = 1e5
laser_x = None
laser_y = None
for i in range(len(position)):
a = position[i][0] - robo_pos[0]
b = position[i][1] - robo_pos[1]
A = 1 + math.tan(th) ** 2
B = -2 * (a + b * math.tan(th))
C = a ** 2 + b ** 2 - r_sq
check_root = round(B ** 2 - 4 * A * C, 12)
if check_root >= 0:
x1 = (-B - math.sqrt(check_root)) / (2 * A)
y1 = x1 * math.tan(th)
x2 = (-B + math.sqrt(check_root)) / (2 * A)
y2 = x2 * math.tan(th)
mag1 = math.sqrt(x1 ** 2 + y1 ** 2)
mag2 = math.sqrt(x2 ** 2 + y2 ** 2)
if mag1 < mag2:
append_x = x1
append_y = y1
dist = mag1
else:
append_x = x2
append_y = y2
dist = mag2
if add_noise:
append_x += truncnorm.rvs(-noise_limit, noise_limit)
append_y += truncnorm.rvs(-noise_limit, noise_limit)
if dist < min_dist:
min_dist = dist
laser_x = append_x + robo_pos[0]
laser_y = append_y + robo_pos[1]
if not (laser_x == None):
x, y = self._coordinate_transform((laser_x, laser_y))
laser_points.append((y, x))
th += scan_res
if len(laser_points) > 2:
convex_hull_vertices = []
hull = ConvexHull(np.array(laser_points))
for i in hull.vertices:
hull_vertice = (laser_points[i][0], laser_points[i][1])
if data_aug:
convex_hull_vertices.append(self._aug_transform(hull_vertice))
else:
convex_hull_vertices.append(hull_vertice)
cv2.fillConvexPoly(frame, np.array(convex_hull_vertices), (255, 255, 255))
if debug:
for i in range(len(convex_hull_vertices)):
cv2.circle(frame, (convex_hull_vertices[i][0],
convex_hull_vertices[i][1]), 2, (0,0,255), 2)
else:
print('Warning: Laser did not pick up any scan point!')
return frame
def _draw_canvas_handler(self, canvas, frame_idx, group_label, data_aug, sim):
positions, velocities, pedidx = self._find_label_properties(frame_idx, group_label)
if sim:
canvas = self._draw_simulated_social_shapes(canvas, positions, data_aug)
else:
canvas = self._draw_social_shapes(canvas, positions, velocities, data_aug)
return canvas, pedidx
def _set_aug_param(self, angle, translation):
self.aug_angle = angle / 180.0 * math.pi
self.aug_trans = translation
return
def _prepare_aug_param(self, frame_idx, group_1, group_2):
#XXX XXX XXX XXX XXX DANGER!!!!!!!!!!!!!
if group_2 == -1:
positions, _, _ = self._find_label_properties(frame_idx, group_1)
center = self._find_centroid(positions)
else:
positions_1, _, _ = self._find_label_properties(frame_idx, group_1)
positions_2, _, _ = self._find_label_properties(frame_idx, group_2)
center = self._find_centroid(positions_1 + positions_2)
center[1], center[0] = self._coordinate_transform(center)
self._set_aug_param(np.random.choice(360),
[self.frame_width / 2 - center[0],
self.frame_height / 2 - center[1]])
return
def _aug_transform(self, coord):
x = coord[0] + self.aug_trans[0]
y = coord[1] + self.aug_trans[1]
x -= self.frame_width / 2
y -= self.frame_height / 2
nx = math.cos(self.aug_angle) * x - math.sin(self.aug_angle) * y
ny = math.sin(self.aug_angle) * x + math.cos(self.aug_angle) * y
nx += self.frame_width / 2
ny += self.frame_height / 2
return (int(nx), int(ny))
def _reverse_aug_transform(self, coord):
x = coord[0]
y = coord[1]
x -= self.frame_width / 2
y -= self.frame_height / 2
nx = math.cos(-self.aug_angle) * x - math.sin(-self.aug_angle) * y
ny = math.sin(-self.aug_angle) * x + math.cos(-self.aug_angle) * y
nx += self.frame_width / 2
ny += self.frame_height / 2
return (int(nx) - self.aug_trans[0], int(ny) - self.aug_trans[1])
def _coordinate_transform(self, coord):
pt = np.matmul(np.linalg.inv(self.H), [[coord[0]], [coord[1]], [1.0]])
x = pt[0][0] / pt[2][0]
y = pt[1][0] / pt[2][0]
if self.dataset == 'ucy':
tmp_y = y
y = self.frame_width / 2 + x
x = self.frame_height / 2 - tmp_y
x = int(round(x))
y = int(round(y))
return x, y
def _reverse_coordinate_transform(self, coord):
x = coord[0]
y = coord[1]
if self.dataset == 'ucy':
tmp_y = y
y = x
x = tmp_y
x = x - self.frame_width / 2
y = self.frame_height / 2 - y
pt = np.matmul(self.H, [[x], [y], [1.0]])
x = pt[0][0] / pt[2][0]
y = pt[1][0] / pt[2][0]
return x, y
def _find_label_properties(self, frame_idx, label):
positions = []
velocities = []
pedidx = []
labels = self.video_labels_matrix[frame_idx]
for i in range(len(labels)):
if label == labels[i]:
positions.append(self.video_position_matrix[frame_idx][i])
velocities.append(self.video_velocity_matrix[frame_idx][i])
pedidx.append(self.video_pedidx_matrix[frame_idx][i])
return positions, velocities, pedidx
def _find_centroid(self, positions):
center = [0, 0]
for ps in positions:
center[0] += ps[0]
center[1] += ps[1]
center[0] = center[0] / float(len(positions))
center[1] = center[1] / float(len(positions))
return center
def _find_action_location(self, frame_idx, label_1, label_2):
positions_1, velocities_1, _ = self._find_label_properties(frame_idx, label_1)
positions_2, velocities_2, _ = self._find_label_properties(frame_idx, label_2)
if (positions_1 == []) or (positions_2 == []):
print(label_1)
print(label_2)
print(self.video_labels_matrix[frame_idx])
raise Exception('no labels in frame!')
return (0, 0)
convex_1 = self._draw_social_shapes([], positions_1, velocities_1, False, False)
convex_2 = self._draw_social_shapes([], positions_2, velocities_2, False, False)
convex_center_1 = self._find_centroid(positions_1)
convex_center_2 = self._find_centroid(positions_2)
convex_center_1[1], convex_center_1[0] = self._coordinate_transform(convex_center_1)
convex_center_2[1], convex_center_2[0] = self._coordinate_transform(convex_center_2)
min_dist_1 = 1000000
min_dist_2 = 1000000
for k in convex_1:
tmp_dist = math.sqrt((k[0] - convex_center_2[0]) ** 2 + (k[1] - convex_center_2[1]) ** 2)
if tmp_dist < min_dist_1:
min_dist_1 = tmp_dist
min_coords_1 = k
for k in convex_2:
tmp_dist = math.sqrt((k[0] - convex_center_1[0]) ** 2 + (k[1] - convex_center_1[1]) ** 2)
if tmp_dist < min_dist_2:
min_dist_2 = tmp_dist
min_coords_2 = k
action_coord = (int(round((min_coords_1[0] + min_coords_2[0]) / 2)),
int(round((min_coords_1[1] + min_coords_2[1]) / 2)))
return action_coord
def _prepare_process_image(self, img_seq):
left = self.frame_width / 2
up = self.frame_height / 2
right = self.frame_width / 2
low = self.frame_height / 2
for img in img_seq:
im = Image.fromarray(np.uint8(img))
bbox = im.getbbox()
if bbox == None:
continue
if bbox[0] < left:
left = bbox[0]
if bbox[1] < up:
up = bbox[1]
if bbox[2] > right:
right = bbox[2]
if bbox[3] > low:
low = bbox[3]
upper_left = (left, up)
lower_right = (right, low)
upper_left_p = (self.frame_width - upper_left[0], self.frame_height - upper_left[1])
lower_right_p = (self.frame_width - lower_right[0], self.frame_height - lower_right[1])
self.bbox_crop = (min(upper_left[0], lower_right[0], upper_left_p[0], lower_right_p[0]),
min(upper_left[1], lower_right[1], upper_left_p[1], lower_right_p[1]),
max(upper_left[0], lower_right[0], upper_left_p[0], lower_right_p[0]),