-
Notifications
You must be signed in to change notification settings - Fork 0
/
action_recognition_alg.py
1959 lines (1834 loc) · 84.2 KB
/
action_recognition_alg.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 sys
import os
import warnings
import logging
import glob
from math import pi
import numpy as np
from numpy.linalg import pinv
import cv2
import class_objects as co
import sparse_coding as sc
import hand_segmentation_alg as hsa
import hist4d as h4d
from matplotlib import pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.widgets import Button
import cPickle as pickle
import time
# Kinect Intrinsics
PRIM_X = 256.92
PRIM_Y = 204.67
FLNT = 365.98
# Senz3d Intrinsics
'''
PRIM_X = 317.37514566554989
PRIM_Y = 246.61273826510859
FLNT = 595.333159044648 / (30.48 / 1000.0)
'''
def initialize_logger(logger):
if not getattr(logger, 'handler_set', None):
CH = logging.StreamHandler()
CH.setFormatter(logging.Formatter(
'%(name)s-%(funcName)s()(%(lineno)s)-%(levelname)s:%(message)s'))
logger.addHandler(CH)
logger.handler_set = True
logger.propagate = False
def checktypes(objects, classes):
'''
Checks type of input objects and prints caller's doc string
and exits if there is a problem
'''
frame = sys._getframe(1)
try:
if not all([isinstance(obj, instance) for
obj, instance in zip(objects, classes)]):
raise TypeError(getattr(frame.f_locals['self'].__class__,
frame.f_code.co_name).__doc__)
finally:
del frame
def timeit(func):
'''
Decorator to time extraction
'''
def wrapper(self,*arg, **kw):
t1 = time.time()
res = func(self,*arg, **kw)
t2 = time.time()
self.time.append(t2-t1)
del self.time[:-5000]
return res
return wrapper
def find_nonzero(arr):
'''
Finds nonzero elements positions
'''
return np.fliplr(cv2.findNonZero(arr).squeeze())
def prepare_dexter_im(img):
'''
Compute masks for images
'''
binmask = img < 6000
contours = cv2.findContours(
(binmask).astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[1]
contours_area = [cv2.contourArea(contour) for contour in contours]
hand_contour = contours[np.argmax(contours_area)].squeeze()
hand_patch = img[np.min(hand_contour[:, 1]):np.max(hand_contour[:, 1]),
np.min(hand_contour[:, 0]):np.max(hand_contour[:, 0])]
hand_patch_max = np.max(hand_patch)
hand_patch[hand_patch == hand_patch_max] = 0
img[img == hand_patch_max] = 0
med_filt = np.median(hand_patch[hand_patch != 0])
thres = np.min(img) + 0.1 * (np.max(img) - np.min(img))
binmask[np.abs(img - med_filt) > thres] = False
hand_patch[np.abs(hand_patch - med_filt) > thres] = 0
hand_patch_pos = np.array(
[np.min(hand_contour[:, 1]), np.min(hand_contour[:, 0])])
return img * binmask,\
hand_patch, hand_patch_pos
def prepare_im(img, contour=None, square=False):
'''
<square> for display reasons, it returns a square patch of the hand, with
the hand centered inside.
'''
if img is None:
return None, None, None
if contour is None:
contours = cv2.findContours(
(img).astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[1]
contours_area = [cv2.contourArea(contour) for contour in contours]
try:
contour = contours[np.argmax(contours_area)].squeeze()
except ValueError:
return None, None, None
hand_contour = contour.squeeze()
if hand_contour.size == 2:
return None, None, None
if square:
edge_size = max(np.max(hand_contour[:, 1]) - np.min(hand_contour[:, 1]),
np.max(hand_contour[:, 0]) - np.min(hand_contour[:, 0]))
center = np.mean(hand_contour, axis=0).astype(int)
hand_patch = img[center[1] - edge_size / 2:
center[1] + edge_size / 2,
center[0] - edge_size / 2:
center[0] + edge_size / 2
]
else:
hand_patch = img[np.min(hand_contour[:, 1]):np.max(hand_contour[:, 1]),
np.min(hand_contour[:, 0]):np.max(hand_contour[:, 0])]
hand_patch_pos = np.array(
[np.min(hand_contour[:, 1]), np.min(hand_contour[:, 0])])
return hand_patch, hand_patch_pos, contour
class SpaceHistogram(object):
'''
Create Histograms for 3DHOG and GHOF
'''
def __init__(self):
self.bin_size = None
self.range = None
def hist_data(self, sample):
'''
Compute normalized N-D histograms
'''
hist, edges = np.histogramdd(sample, self.bin_size, range=self.range)
return hist, edges
class BufferOperations(object):
def __init__(self, parameters, reset_time=True):
self.logger = logging.getLogger('BufferOperations')
initialize_logger(self.logger)
self.parameters = parameters
self.buffer = []
self.depth = []
self.testing = parameters['testing']
self.action_type = parameters['action_type']
self.samples_indices = []
self.buffer_start_inds = []
self.buffer_end_inds = []
if not self.action_type == 'Passive':
self.ptpca = parameters['PTPCA']
self.ptpca_components = parameters['PTPCA_params'][
'PTPCA_components']
self.bbuffer = [[] for i in range(len(parameters['descriptors']))]
if not self.action_type == 'Passive':
self.buffer_size = parameters['dynamic_params']['buffer_size']
try:
self.buffer_confidence_tol = parameters['dynamic_params'][
'buffer_confidence_tol']
self.ptpca = parameters['PTPCA']
self.ptpca_components = parameters['PTPCA_params'][
'PTPCA_components']
except (KeyError, IndexError, TypeError):
self.buffer_confidence_tol = None
self.pca_features = []
else:
self.buffer_size = 1
self.sync = []
self.frames_inds = []
self.samples_inds = []
self.buffer_components = []
self.depth_components = []
self.real_samples_inds = []
if reset_time:
self.time = []
def reset(self, reset_time=False):
self.__init__(self.parameters, reset_time=reset_time)
def check_buffer_integrity(self, buffer):
check_sam = True
check_cont = True
check_len = len(buffer) == self.buffer_size
if check_len:
if not self.action_type == 'Passive':
check_cont = np.all(np.abs(np.diff(self.frames_inds[-self.buffer_size:])) <=
self.buffer_size * self.buffer_confidence_tol)
# check if buffer frames belong to the same sample, in case of
# training
check_sam = self.testing or len(np.unique(
self.samples_inds[-self.buffer_size:])) == 1
else:
check_cont = True
check_sam = True
check_len = True
return check_len and check_cont and check_sam
@timeit
def perform_post_time_pca(self, inp):
reshaped = False
if self.buffer_size == 1:
return
if np.shape(inp)[0] == 1 or len(np.shape(inp))==1:
reshaped = True
inp = np.reshape(inp, (self.buffer_size, -1))
mean, inp = cv2.PCACompute(
np.array(inp),
np.array([]),
maxComponents=self.ptpca_components)
inp = (np.array(inp) + mean)
if reshaped:
return inp.ravel()
return inp
def update_buffer_info(self, sync, samples_index=0,
samples=None, depth=None):
self.frames_inds.append(sync)
self.samples_inds.append(samples_index)
if samples is not None:
self.buffer_components.append(samples)
del self.buffer_components[:-self.buffer_size]
if depth is not None:
self.depth_components.append(depth)
del self.depth_components[:-self.buffer_size]
def add_buffer(self, buffer=None, depth=None, sample_count=None,
already_checked=False):
'''
<buffer> should have always the same size.
<self.bbuffer> is a list of buffers. It can have a size limit, after which it
acts as a buffer (useful for shifting window
operations (filtering etc.))
'''
# check buffer contiguousness
if buffer is None:
buffer = self.buffer_components
if depth is None:
fmask = np.isfinite(self.depth_components)
if np.sum(fmask):
depth = np.mean(np.array(self.depth_components)[fmask])
if not already_checked:
check = self.check_buffer_integrity(buffer[-self.buffer_size:])
else:
check = True
if not self.parameters['testing_params']['online']:
self.real_samples_inds += [-1] * (self.frames_inds[-1] + 1 -
len(self.buffer))
self.depth += [None] * (self.frames_inds[-1] + 1
- len(self.buffer))
self.buffer += [None] * (self.frames_inds[-1] + 1
- len(self.buffer))
if check:
self.buffer_start_inds.append(self.frames_inds[-self.buffer_size])
self.buffer_end_inds.append(self.frames_inds[-1])
if not self.parameters['testing_params']['online']:
self.buffer[self.frames_inds[-1]] = np.array(
buffer)
self.depth[self.frames_inds[-1]] = depth
else:
self.buffer = np.array(buffer)
self.depth = depth
if not self.parameters['testing_params']['online']:
self.real_samples_inds[self.frames_inds[-1]] = (np.unique(self.samples_inds[
-self.buffer_size:])[0])
else:
if self.parameters['testing_params']['online']:
self.buffer = None
self.depth = None
def extract_buffer_list(self):
'''
Returns a 2d numpy array, which has as first dimension the number of
saved features sets inside <self.bbuffer>,
as second dimension a flattened buffer. In case it is online, the first
dimension is 1. In case there are None samples inside, those are turned
to None arrays.
'''
if self.parameters['testing_params']['online']:
if self.bbuffer is None:
return None
else:
buffer_len = 0
for _buffer in self.buffer:
if _buffer is not None:
buffer_len = np.size(_buffer)
break
if not buffer_len:
self.logger.debug('No valid buffer')
return None
npbuffer = np.zeros((len(self.buffer),buffer_len))
for buffer_count in range(len(self.buffer)):
if self.buffer[buffer_count] is None:
self.buffer[buffer_count] = np.zeros(buffer_len)
self.buffer[buffer_count][:] = np.nan
npbuffer[buffer_count, ...] =\
np.array(self.buffer[buffer_count]).T.ravel()
return npbuffer, self.real_samples_inds, self.depth
class Action(object):
'''
Class to hold an action
'''
def __init__(self, parameters, name, coders=None):
self.name = name
self.parameters = parameters
self.features = []
self.sync = []
self.frames_inds = []
self.samples_inds = []
self.length = 0
self.start_inds = []
self.end_inds = []
self.real_data = []
class Actions(object):
'''
Class to hold multiple actions
'''
def __init__(self, parameters, coders=None, feat_filename=None):
self.logger = logging.getLogger(self.__class__.__name__)
initialize_logger(self.logger)
self.slflogger = logging.getLogger('save_load_features')
FH = logging.FileHandler('save_load_features.log', mode='w')
FH.setFormatter(logging.Formatter(
'%(asctime)s (%(lineno)s): %(message)s',
"%Y-%m-%d %H:%M:%S"))
self.slflogger.addHandler(FH)
self.slflogger.setLevel(logging.INFO)
self.parameters = parameters
self.sparsecoded = parameters['sparsecoded']
self.available_descriptors = {'3DHOF': Descriptor3DHOF,
'ZHOF': DescriptorZHOF,
'GHOG': DescriptorGHOG,
'3DXYPCA': Descriptor3DXYPCA}
self.actions = []
self.names = []
self.coders = coders
if coders is None:
self.coders = [None] * len(self.parameters['descriptors'])
self.save_path = (os.getcwd() +
os.sep + 'saved_actions.pkl')
self.features_extract = None
self.preproc_time = []
self.features_db = None
self.feat_filename = feat_filename
self.candid_d_actions = None
self.valid_feats = None
self.all_data = [None] * len(self.parameters['descriptors'])
self.name = None
self.frames_preproc = None
self.descriptors = {feature:None for feature in
self.parameters['descriptors']}
self.descriptors_id = [None] * len(self.parameters['descriptors'])
self.coders_info = [None] * len(self.parameters['descriptors'])
self.buffer_class= ([BufferOperations(self.parameters)] *
len(self.parameters['descriptors']))
def save_action_features_to_mem(self, data, filename=None,
action_name=None):
'''
features_db has tree structure, with the following order:
features type->list of instances dicts ->[params which are used to
identify the features, data of each instance->actions]
This order allows to search only once for each descriptor and get all
actions corresponding to a matching instance, as it is assumed that
descriptors are fewer than actions.
<data> is a list of length same as the descriptors number
'''
if filename is None:
if self.feat_filename is None:
return
else:
filename = self.feat_filename
if action_name is None:
action_name = self.name
for dcount, descriptor in enumerate(
self.parameters['descriptors']):
if self.candid_d_actions[dcount] is None:
self.candid_d_actions[dcount] = {}
self.candid_d_actions[dcount][action_name] = data[dcount]
co.file_oper.save_labeled_data([descriptor,
str(co.dict_oper.
create_sorted_dict_view(
self.parameters[
'features_params'][
descriptor]))],
self.candid_d_actions[dcount],
filename, fold_lev=1)
def load_action_features_from_mem(self, filename=None):
'''
features_db has tree structure, with the following order:
features type->list of instances dicts ->[params which are used to
identify the features, data of each instance->actions]
This order allows to search only once for each descriptor and get all
actions corresponding to a matching instance, as it is assumed that
descriptors are fewer than actions
'''
features_to_extract = self.parameters['descriptors'][:]
data = [None] * len(features_to_extract)
if self.candid_d_actions is None:
self.candid_d_actions = []
if filename is None:
if self.feat_filename is None:
return features_to_extract, data
else:
filename = self.feat_filename
for descriptor in self.parameters['descriptors']:
self.candid_d_actions.append(
co.file_oper.load_labeled_data([descriptor,
str(co.dict_oper.create_sorted_dict_view(
self.parameters[
'features_params'][
descriptor]))],
filename, fold_lev=1))
'''
Result is <candid_d_actions>, a list which holds matching
instances of actions for each descriptor, or None if not found.
'''
for dcount, instance in enumerate(self.candid_d_actions):
self.slflogger.info('Descriptor: ' + self.parameters['descriptors'][
dcount])
if instance is not None:
self.slflogger.info('Finding action \'' + self.name +
'\' inside matching instance')
if self.name in instance and np.array(
instance[self.name][0]).size > 0:
self.slflogger.info('Action Found')
data[dcount] = instance[self.name]
features_to_extract.remove(self.parameters['descriptors']
[dcount])
else:
self.slflogger.info('Action not Found')
else:
self.slflogger.info('No matching instance exists')
return features_to_extract, data
def train_sparse_dictionary(self):
'''
Train missing sparse dictionaries. add_action should have been executed
first
'''
for count, (data, info) in enumerate(
zip(self.all_data, self.coders_info)):
if not self.coders[count]:
if data is not None:
coder = sc.SparseCoding(
sparse_dim_rat=self.parameters['features_params'][
self.parameters['descriptors'][count]][
'sparse_params']['_dim_rat'],
name=self.parameters['descriptors'][count])
finite_samples = np.prod(np.isfinite(data),
axis=1).astype(bool)
coder.train_sparse_dictionary(data[finite_samples,:])
co.file_oper.save_labeled_data(info, coder)
else:
raise Exception('No data available, run add_action first')
self.coders[count] = coder
co.file_oper.save_labeled_data(self.coders_info[count], self.coders[count])
def load_sparse_coder(self, count):
self.coders_info[count] = (['Sparse Coders']+
[self.parameters['sparsecoded']]+
[str(self.parameters['descriptors'][
count])]+
[str(co.dict_oper.create_sorted_dict_view(
self.parameters['coders_params'][
str(self.parameters['descriptors'][count])]))])
if self.coders[count] is None:
self.coders[count] = co.file_oper.load_labeled_data(
self.coders_info[count])
return self.coders_info[count]
def retrieve_descriptor_possible_ids(self, count, assume_existence=False):
descriptor = self.parameters['descriptors'][count]
file_ids = [co.dict_oper.create_sorted_dict_view(
{'Descriptor':descriptor}),
co.dict_oper.create_sorted_dict_view(
{'ActionType':self.parameters['action_type']}),
co.dict_oper.create_sorted_dict_view(
{'DescriptorParams':co.dict_oper.create_sorted_dict_view(
self.parameters['features_params'][descriptor]['params'])})]
ids = ['Features']
if self.sparsecoded:
self.load_sparse_coder(count)
if (self.parameters['sparsecoded'] == 'Features'
and (self.coders[count] is not None or assume_existence)):
file_ids.append(co.dict_oper.create_sorted_dict_view(
{'SparseFeaturesParams':
co.dict_oper.create_sorted_dict_view(
self.parameters[
'features_params'][descriptor]['sparse_params'])}))
ids.append('Sparse Features')
file_ids.append(co.dict_oper.create_sorted_dict_view(
{'BufferParams':
co.dict_oper.create_sorted_dict_view(
self.parameters['dynamic_params'])}))
ids.append('Buffered Features')
if self.parameters['action_type']!='Passive':
if (self.parameters['sparsecoded'] == 'Buffer'
and (self.coders[count] is not None or assume_existence)):
file_ids.append(co.dict_oper.create_sorted_dict_view(
{'SparseBufferParams':
co.dict_oper.create_sorted_dict_view(
self.parameters[
'features_params'][descriptor]['sparse_params'])}))
ids.append('Sparse Buffers')
if not (self.parameters['sparsecoded'] == 'Buffer'
and self.coders[count] is None) or assume_existence:
if self.parameters['PTPCA']:
file_ids.append(co.dict_oper.create_sorted_dict_view(
{'PTPCAParams':
co.dict_oper.create_sorted_dict_view(
self.parameters[
'PTPCA_params'])}))
ids.append('PTPCA')
return ids, file_ids
def add_action(self, data=None,
mv_obj_fold_name=None,
hnd_mk_fold_name=None,
masks_needed=True,
use_dexter=False,
visualize_=False,
isderotated=False,
action_type='Dynamic',
max_act_samples=None,
fss_max_iter=None,
derot_centers=None,
derot_angles=None,
name=None,
feature_extraction_method=None,
save=True,
load=True,
feat_filename=None,
calc_mean_depths=False,
to_visualize=[],
n_vis_frames=9,
exit_after_visualization=False,
offline_vis=False):
'''
parameters=dictionary having at least a 'descriptors' key, which holds
a sublist of ['3DXYPCA', 'GHOG', '3DHOF', 'ZHOF']. It can have a
'features_params' key, which holds specific parameters for the
features to be extracted.
features_extract= FeatureExtraction Class
data= (Directory with depth frames) OR (list of depth frames)
use_dexter= True if Dexter 1 TOF Dataset is used
visualize= True to visualize features extracted from frames
'''
self.name = name
if name is None:
self.name = os.path.basename(data)
loaded_data = [[] for i in range(len(self.parameters['descriptors']))]
readimagedata = False
features = [None] * len(self.parameters['descriptors'])
buffers = [None] * len(self.parameters['descriptors'])
samples_indices = [None] * len(self.parameters['descriptors'])
median_depth = [None] * len(self.parameters['descriptors'])
times = {}
valid = False
redo = False
if 'raw' in to_visualize:
load = False
while not valid:
for count, descriptor in enumerate(self.parameters['descriptors']):
nloaded_ids = {}
loaded_ids = {}
ids, file_ids = self.retrieve_descriptor_possible_ids(count)
try_ids = ids[:]
for try_count in range(len(try_ids)):
loaded_data = co.file_oper.load_labeled_data(
[try_ids[-1]] + file_ids + [self.name])
if loaded_data is not None and not redo and load:
loaded_ids[try_ids[-1]] = file_ids[:]
break
else:
nloaded_ids[try_ids[-1]] = file_ids[:]
try_ids = try_ids[:-1]
file_ids = file_ids[:-1]
for _id in ids:
try:
nloaded_file_id = nloaded_ids[_id]
nloaded_id = _id
except:
continue
if nloaded_id == 'Features':
if not readimagedata:
(imgs, masks, sync, angles,
centers,
samples_inds) = co.imfold_oper.load_frames_data(
data,mv_obj_fold_name,
hnd_mk_fold_name, masks_needed,
derot_centers,derot_angles)
if 'raw' in to_visualize:
montage = co.draw_oper.create_montage(imgs[:],
max_ims=n_vis_frames,
draw_num=False)
fig = plt.figure()
tmp_axes = fig.add_subplot(111)
tmp_axes.imshow(montage[:,:,:-1])
plt.axis('off')
fig.savefig('frames_sample.pdf',
bbox_inches='tight')
to_visualize.remove('raw')
if (not to_visualize and
exit_after_visualization):
return
for cnt in range(len(samples_indices)):
samples_indices[cnt] = samples_inds.copy()
readimagedata = True
if not self.frames_preproc:
self.frames_preproc = FramesPreprocessing(self.parameters)
else:
self.frames_preproc.reset()
if not self.descriptors[descriptor]:
self.descriptors[
descriptor] = self.available_descriptors[
descriptor](parameters=self.parameters,
datastreamer=self.frames_preproc,
viewer=(
FeatureVisualization(
offline_vis=offline_vis,
n_frames=len(imgs)) if
to_visualize else None))
else:
self.descriptors[descriptor].reset()
features[count] = []
median_depth[count] = []
valid = []
for img_count, img in enumerate(imgs):
'''
#DEBUGGING
cv2.imshow('t', (img%256).astype(np.uint8))
cv2.waitKey(30)
'''
check = self.frames_preproc.update(img,
sync[img_count],
mask=masks[img_count],
angle=angles[img_count],
center=centers[img_count])
if 'features' in to_visualize:
self.descriptors[descriptor].set_curr_frame(img_count)
if check:
extracted_features = self.descriptors[descriptor].extract()
if extracted_features is not None:
features[count].append(extracted_features)
median_depth[count].append(np.median(self.frames_preproc.curr_patch))
else:
features[count].append(None)
median_depth[count].append(None)
if 'features' in to_visualize:
self.descriptors[descriptor].visualize()
self.descriptors[descriptor].draw()
if (len(to_visualize) == 1 and
exit_after_visualization):
continue
else:
if (len(to_visualize) == 1
and exit_after_visualization):
self.descriptors[descriptor].draw()
continue
features[count].append(None)
median_depth[count].append(None)
if 'Features' not in times:
times['Features'] = []
times['Features'] += self.descriptors[descriptor].time
if self.preproc_time is None:
self.preproc_time = []
self.preproc_time+=self.frames_preproc.time
loaded_ids[nloaded_id] = nloaded_file_id
co.file_oper.save_labeled_data([nloaded_id]
+loaded_ids[nloaded_id]+
[self.name],
[np.array(features[count]),
(sync,
samples_indices[count]),
median_depth[count],
times])
elif nloaded_id == 'Sparse Features':
if features[count] is None:
[features[count],
(sync,
samples_indices[count]),
median_depth[count],
times] = co.file_oper.load_labeled_data(
[ids[ids.index(nloaded_id)-1]]+
loaded_ids[ids[ids.index(nloaded_id)-1]]+[self.name])
if self.coders[count] is None:
self.load_sparse_coder(count)
features[count] = self.coders[
count].multicode(features[count])
if 'Sparse Features' not in times:
times['Sparse Features'] = []
times['Sparse Features'] += self.coders[
count].time
loaded_ids[nloaded_id] = nloaded_file_id
co.file_oper.save_labeled_data([nloaded_id] +
loaded_ids[nloaded_id]+
[self.name],
[np.array(features[count]),
(sync,
samples_indices[count]),
median_depth[count],
times])
elif nloaded_id == 'Buffered Features':
if features[count] is None or samples_indices[count] is None:
[features[
count],
(sync,
samples_indices[count]),
median_depth[count],
times] = co.file_oper.load_labeled_data(
[ids[ids.index(nloaded_id) -1]] +
loaded_ids[
ids[ids.index(nloaded_id) - 1]] +
[self.name])
self.buffer_class[count].reset()
new_samples_indices = []
for sample_count in range(len(features[count])):
self.buffer_class[count].update_buffer_info(
sync[sample_count],
samples_indices[count][sample_count],
samples = features[count][sample_count],
depth=median_depth[count][sample_count])
self.buffer_class[count].add_buffer()
features[count],samples_indices[count],median_depth[count] = self.buffer_class[count].extract_buffer_list()
loaded_ids[nloaded_id] = nloaded_file_id
co.file_oper.save_labeled_data([nloaded_id]+loaded_ids[nloaded_id]
+[self.name],
[np.array(features[count]),
samples_indices[count],
median_depth[count],
times])
elif nloaded_id == 'Sparse Buffers':
if features[count] is None:
[features[count],
samples_indices[count],
median_depth[count],
times] = co.file_oper.load_labeled_data(
['Buffered Features']+loaded_ids['Buffered Features']
+[self.name])
if self.coders[count] is None:
self.load_sparse_coder(count)
features[count] = self.coders[count].multicode(features[count])
if 'Sparse Buffer' not in times:
times['Sparse Buffer'] = []
times['Sparse Buffer'] += self.coders[
count].time
loaded_ids[nloaded_id] = nloaded_file_id
co.file_oper.save_labeled_data([nloaded_id] +
loaded_ids[nloaded_id]
+[self.name],
[np.array(features[count]),
samples_indices[count],
median_depth[count],
times])
elif nloaded_id == 'PTPCA':
if features[count] is None:
[features[count],
samples_indices[count],
median_depth[count],
times] = co.file_oper.load_labeled_data(
[ids[ids.index('PTPCA')-1]] +
loaded_ids[ids[ids.index('PTPCA') - 1]]
+[self.name])
self.buffer_class[count].reset()
features[count] = [
self.buffer_class[count].perform_post_time_pca(
_buffer) for _buffer in features[count]]
if 'PTPCA' not in times:
times['PTPCA'] = []
times['PTPCA'] += self.buffer_class[
count].time
loaded_ids[nloaded_id] = nloaded_file_id
co.file_oper.save_labeled_data([nloaded_id] +
loaded_ids[nloaded_id]+
[self.name],
[np.array(
features[count]),
samples_indices[count],
median_depth[count],
times])
if features[count] is None:
try:
[features[count],
samples_indices[count],
median_depth[count],
times] = loaded_data
if isinstance(samples_indices[count], tuple):
samples_indices[count] = samples_indices[count][-1]
except TypeError:
pass
self.descriptors_id[count] = loaded_ids[ids[-1]]
if (self.parameters['sparsecoded'] and not self.coders[count]):
finite_features = []
for feat in features[count]:
if feat is not None:
finite_features.append(feat)
if self.all_data[count] is None:
self.all_data[count] = np.array(finite_features)
else:
self.all_data[count] = np.concatenate((self.all_data[count],
finite_features),axis=0)
try:
if np.unique([len(feat) for feat in features]).size == 1:
valid = True
redo = False
else:
self.logger.warning('Unequal samples dimension of loaded features:'
+ str([len(feat) for feat in features])
+' ...repeating')
redo = True
except Exception as e:
for count,feat in enumerate(features):
if feat is None:
print 'Features[' + str(count) + '] is None'
self.logger.warning(str(e))
redo = True
pass
return (features,
samples_indices[np.argmax([len(sample) for sample in
samples_indices])],
median_depth[np.argmax([len(median_depth) for
median_depth in
samples_indices])],
self.name, self.coders, self.descriptors_id)
def save(self, save_path=None):
'''
Save actions to file
'''
if save_path is None:
actions_path = self.save_path
else:
actions_path = save_path
self.logger.info('Saving actions to ' + actions_path)
with open(actions_path, 'wb') as output:
pickle.dump(self.actions, output, -1)
class ActionsSparseCoding(object):
'''
Class to hold sparse coding coders
'''
def __init__(self, parameters):
self.features = parameters['descriptors']
self.logger = logging.getLogger(self.__class__.__name__)
initialize_logger(self.logger)
self.parameters = parameters
self.sparse_dim_rat = []
try:
for feat in self.features:
self.sparse_dim_rat.append(parameters['sparse_params'][feat])
except (KeyError, TypeError):
self.sparse_dim_rat = [None] * len(self.features)
self.sparse_coders = []
self.codebooks = []
self.initialized = True
self.save_path = (os.getcwd() +
os.sep + 'saved_coders.pkl')
def train(self, data, feat_count, display=0, min_iterations=10,
init_traindata_num=200, incr_rate=2, sp_opt_max_iter=200,
debug=False, save_traindata=True):
'''
feat_count: features position inside
actions.actions[act_num].features list
'''
try:
self.sparse_coders[feat_count].display = display
except:
self.sparse_coders[feat_count] = sc.SparseCoding(
sparse_dim_rat=self.sparse_dim_rat[feat_count],
name=str(feat_count))
self.sparse_coders[feat_count].display = display
self.logger.info('Training Dictionaries using data of shape:'
+ str(data.shape))
if save_traindata:
savepath = ('SparseTraining-' +
self.parameters['descriptors'][
feat_count] + '.npy')
self.logger.info('TrainData is saved to ' + savepath)
np.save(savepath, data, allow_pickle=False)
self.sparse_coders[feat_count].train_sparse_dictionary(data,
init_traindata_num=init_traindata_num,
incr_rate=incr_rate,
sp_opt_max_iter=sp_opt_max_iter,
min_iterations=min_iterations,
n_jobs=4)
self.codebooks[feat_count] = (
pinv(self.sparse_coders[feat_count].codebook_comps))
return 1
def initialize(self):
'''
initialize / reset all codebooks that refer to the given <sparse_dim_rat>
and feature combination
'''
self.sparse_coders = []
for count, feature in enumerate(self.features):
self.sparse_coders.append(sc.SparseCoding(
sparse_dim_rat=self.sparse_dim_rat[count],
name=str(count)))
self.codebooks.append(None)
self.initialized = True
def flush(self, feat_count='all'):
'''
Reinitialize all or one dictionary
'''
if feat_count == 'all':
iter_quant = self.sparse_coders
iter_range = range(len(self.features))
else:
iter_quant = [self.sparse_coders[feat_count]]
iter_range = [feat_count]
feat_dims = []
for feat_count, inv_dict in zip(iter_range, iter_quant):
feat_dims[feat_count] = None
try:
feat_dim = inv_dict.codebook_comps.shape[0]
feat_dims[feat_count] = feat_dim
except AttributeError:
feat_dims[feat_count] = None
for feature in self.sparse_coders:
if feat_dims[feature] is not None:
self.sparse_coders[feat_count].flush_variables()
self.sparse_coders[feat_count].initialize(feat_dims[feature])
def save(self, save_dict=None, save_path=None):
'''
Save coders to file
'''
if save_dict is not None:
for feat_count, feature in enumerate(self.features):
if not self.parameters['PTPCA']:
save_dict[feature + ' ' +
str(self.sparse_dim_rat[feat_count])] = \
self.sparse_coders[feat_count]
else:
save_dict[feature + ' ' +
str(self.sparse_dim_rat[feat_count]) +
' PCA ' +
str(self.parameters['PTPCA_params'][
'PTPCA_components'])] = \
self.sparse_coders[feat_count]
return
if save_path is None:
coders_path = self.save_path
else:
coders_path = save_path
self.logger.info('Saving Dictionaries to ' + coders_path)
with open(coders_path, 'wb') as output:
pickle.dump((self.sparse_coders, self.codebooks), output, -1)
def grad_angles(patch):
'''
Compute gradient angles on image patch for GHOG
'''
y_size = 30
x_size = int(y_size/float(np.shape(patch)[0])
* np.shape(patch)[1])
patch = cv2.resize(patch, (x_size, y_size),
interpolation=cv2.INTER_NEAREST)
grady, gradx = np.gradient(patch)
ang = np.arctan2(grady, gradx)
#ang[ang < 0] = ang[ang < 0] + pi
return ang.ravel() # returns values 0 to pi