-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmartVidCrop.py
2849 lines (2388 loc) · 87.5 KB
/
smartVidCrop.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
# basic imports
import copy
import math
import os
import pathlib
import sys
import numpy as np
from numpy.lib.stride_tricks import as_strided
import pickle
import gc
import ntpath
import zipfile
# for calling ffmpeg to merge video and sound
import subprocess
# OpenCV for reading images from disk
import cv2
# for saving demo
import ffmpeg
# utils for clustering
import hdbscan
# imutils for fast video reading
from imutils.video import FileVideoStream
from scipy.sparse import coo_matrix
from sklearn.cluster import KMeans
# for statistics calculation
import statistics
# SciPy's interpolation
from scipy import interpolate
# SciPy's butterworth lowpass filters
from scipy import signal
from scipy.signal import medfilt
# SciPy's Savitzky-Golay filter (alternative to LOESS)
from scipy.signal import savgol_filter
import matplotlib.pyplot as plt
# get path that the current script file is in
root_path = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
### 3rd party libs loading
# DCNN-based shot segmentation using TransNet
import tensorflow as tf
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.1)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
transnetv1_full_path = os.path.join(root_path, '3rd_party_libs', 'transnetv1')
print(' (adding path %s)' % transnetv1_full_path)
sys.path.insert(0, transnetv1_full_path)
print(' loading transnet v1 model')
import transnetv1_handler
stn_params = transnetv1_handler.ShotTransNetParams()
stn_params.CHECKPOINT_PATH = os.path.join(root_path, '3rd_party_libs', 'transnetv1', 'transnet_model-F16_L3_S2_D256')
trans_threshold = 0.1
transnet_model = transnetv1_handler.ShotTransNet(stn_params, session=sess)
TRANSNET_H = 27
TRANSNET_W = 48
# DCNN-based Saliency detection using UNISAL
import torch
unisal_full_path = os.path.join(root_path, '3rd_party_libs', 'unisal')
gpu_device = torch.device('cuda:0')
print(' (adding path %s)' % unisal_full_path)
sys.path.insert(0, unisal_full_path)
print(' loading unisal model')
import unisal_handler
unisal_model = unisal_handler.init_unisal_for_images()
# Loess local weighted regression
loess_full_path = os.path.join(root_path, '3rd_party_libs', 'loess')
print(' (adding path %s)' % loess_full_path)
sys.path.insert(0, loess_full_path)
import pyloess
def get_video_duration(video_filepath):
cap = cv2.VideoCapture(video_filepath)
fps = float(cap.get(cv2.CAP_PROP_FPS) )
frame_count = float(cap.get(cv2.CAP_PROP_FRAME_COUNT))
duration = float(frame_count/fps)
del cap
return duration
# Methods to initiate the time dictionary,
# register a time in time dictionary,
# and print the time dictionary
sc_times = {}
def sc_init_time():
global sc_times
sc_times = {}
def sc_register_time(t, key_name):
add_t = (cv2.getTickCount() - t) / cv2.getTickFrequency()
if key_name in sc_times.keys():
sc_times[key_name] += add_t
else:
sc_times[key_name] = add_t
def sc_save_time_override(key_name, t):
sc_times[key_name] = t
def sc_all_times(vid_dur):
t_dict = {}
sum_t = 0
sum_p = 0
for key_name in sc_times.keys():
if key_name.startswith('_'):
sum_t += sc_times[key_name]
sum_p += (sc_times[key_name] / vid_dur) * 100.0
t_dict[key_name] ='%7.3fs, %6.3f%%' % (sc_times[key_name],
(sc_times[key_name]/vid_dur)*100.0)
t_dict['total'] = '%7.3fs, %6.3f%%' % (sum_t, sum_p)
return t_dict
def sc_get_time(key_name):
return sc_times[key_name]
# Initiates the SmartVidCrop method's parameters to the default settings
def sc_init_crop_params(print_dict=False, use_best_settings=False):
crop_params = {}
crop_params['out_ratio'] = "4:5"
crop_params['max_input_d'] = 250
crop_params['skip'] = 6
crop_params['read_batch'] = 2000
crop_params['resize_factor'] = 1.0
crop_params['resize_type'] = 1 # 1: bilinear interp.,
# 2: cubic interp.
# 3: nearest
crop_params['op_close'] = True
crop_params['value_bias'] = 1.0 # bias conversion of image value
# to 3rd dimension for clustering
crop_params['exit_on_spread_sal'] = False
crop_params['exit_on_low_cvrg'] = False
crop_params['com_km'] = True # perform kmeans for center of mass,
# else return position of max val
crop_params['clust_filt'] = True
crop_params['select_sum'] = 2 # if 1, select cluster with max sum,
# else select cluster with max value
crop_params['min_d_jump'] = 10 # min pixels distance of a center
# jumps to take into consideration
crop_params['focus_stability'] = False
crop_params['foces_stab_t'] = 60
crop_params['foces_stab_s'] = 1.5
crop_params['hdbscan_min'] = 26
crop_params['hdbscan_min_samples'] = None
crop_params['shift_time'] = 0
crop_params['loess_filt'] = 1
crop_params['loess_w_secs'] = 2
crop_params['loess_degree'] = 2
crop_params['lp_filt'] = 1
crop_params['lp_cutoff'] = 2
crop_params['lp_order'] = 5
crop_params['t_sal'] = 40 # max mean saliency to continue (if higher than this -> pad)
crop_params['t_cvrg'] = 0.60 # min coverage to continue (if lower than this -> pad)
crop_params['t_threshold'] = 120
crop_params['t_border'] = -1 # set to -1 to disable border detection
crop_params['t_cut'] = 120 # if lower than this then a jump over a low saliency area
# was made and extra cut will be inserted
if use_best_settings:
crop_params['t_threshold'] = 90
crop_params['hdbscan_min'] = 5
crop_params['hdbscan_min_samples'] = 3
crop_params['min_d_jump'] = 1
crop_params['resize_factor'] = 4
crop_params['op_close'] = True
crop_params['value_bias'] = 1.0
crop_params['select_sum'] = 1 ####
crop_params['focus_stability'] = True
crop_params['foces_stab_t'] = 60 # 50 # 50.750
crop_params['foces_stab_s'] = 1.5
crop_params['t_border'] = -1
crop_params['lp_filt'] = 1
crop_params['lp_cutoff'] = 1
crop_params['lp_order'] = 2
crop_params['loess_filt'] = 0
if print_dict:
for x in crop_params.keys():
print(x, ':', crop_params[x])
return crop_params
# converts an array of probabilities to a structure of shot boundaries
def predictions_to_scenes(predictions: np.ndarray, threshold: float = 0.5):
predictions = (predictions > threshold).astype(np.uint8)
scenes = []
t, t_prev, start = -1, 0, 0
for i, t in enumerate(predictions):
if t_prev == 1 and t == 0:
start = i
if t_prev == 0 and t == 1 and i != 0:
scenes.append([start, i])
t_prev = t
if t == 0:
scenes.append([start, i])
# just fix if all predictions are 1
if len(scenes) == 0:
return np.array([[0, len(predictions) - 1]], dtype=np.int32)
return np.array(scenes, dtype=np.int32)
# Reads a video, performs shot and saliency detection
# return segmentation info and samples saliency mapsd
def read_and_segment_video(video_path, crop_params, verbose=False):
t_total = cv2.getTickCount()
# open video, get info and close it
print(' ingesting %s...' % video_path)
vcap = cv2.VideoCapture(video_path)
fr = vcap.get(cv2.CAP_PROP_FPS)
frame_count = int(vcap.get(cv2.CAP_PROP_FRAME_COUNT))
w = int(vcap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(vcap.get(cv2.CAP_PROP_FRAME_HEIGHT))
vcap.release()
del vcap
# compute batch size based on frame rate
batch_size = crop_params['read_batch']
batch_overlap = int(fr-5)
# compute frames size for saliency detection
dsr = float(max(w,h)) / crop_params['max_input_d']
SAL_H = int(h/dsr)
SAL_W = int(w/dsr)
# init an array to hold the resized frames for
# shot segmentation
transnet_frames = np.zeros((batch_size+batch_overlap,
TRANSNET_H, TRANSNET_W, 3),
dtype=np.uint8)
# will hold the transition probs for all and selected frames
trans_probs = []
trans_probs_sel = []
# init an array to hold the resized frames for
# saliency detection
frames = np.zeros((batch_size,
SAL_H, SAL_W, 3),
dtype=np.uint8)
# init video data dictionary
vid_data = {}
# estimate number of frames taking into account skipped onew
fcs = 0
skip = crop_params['skip']
for i in range(frame_count):
if (i%skip==0) or (i==0) or i==(frame_count-1):
fcs += 1
fcs += int(frame_count*0.1)
if verbose:
print(' (estimating %d sal. maps)' % fcs)
# init an array to hold saliency maps
vid_data['smaps'] = np.zeros((SAL_H, SAL_W, fcs),
dtype=np.uint8)
# init a list to hold true indices of processed frames
true_inds = [] # in=sampled frame index, out=respective true frame index
map2orig = [] # in=true frame index, out=respective sampled frame index
# init current batch size and batch count
bc = 0
bsi = -1
total_process_ind = -1
# setup fast video reader
fvs = FileVideoStream(video_path).start()
iii = -1
# register read_init time
sc_register_time(t_total, 'read_init')
# loop through video
bail_out = False
after_shot_change = False
while fvs.more():
# set timer for "read" time
t = cv2.getTickCount()
# show header and try to load frame
if (iii%50==0) or (iii>frame_count-50):
print('\r reading %d/%d ' % (iii+1, frame_count), end='', flush=True)
frame = fvs.read()
if frame is None:
bail_out = True
else:
# increment indices
iii += 1
bsi += 1
# convert frame to RGB
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# register frame for shot segmentation
transnet_frames[batch_overlap+bsi,:,:,:] = cv2.resize(frame,
(TRANSNET_W, TRANSNET_H),
interpolation=cv2.INTER_LINEAR)
# register frame for shot segmentation
frames[bsi,:,:,:] = cv2.resize(frame,
(SAL_W, SAL_H),
interpolation=cv2.INTER_LINEAR)
# compute current batch
cur_batch_len = bsi+1
# register read time
sc_register_time(t, '_read')
# process frames if we have a complete or the last batch
if cur_batch_len==batch_size or bail_out:
# if new batch is empty break
if cur_batch_len==0:
break
# set timer for "read_shot_det" time
t = cv2.getTickCount()
# if not 1st batch, append batch overlap to shot detection frames
if bc>0:
prev_batch_len = prev_transnet_frames.shape[0]
for i in range(batch_overlap):
transnet_frames[i,:,:,:] = prev_transnet_frames[prev_batch_len-batch_overlap+i,:,:,:]
prev_transnet_frames = np.copy(transnet_frames)
# comput start and end save indices for shot detection
si = bc*batch_size
ei = si+cur_batch_len
# print info
print('\r reading %d/%d ' % (iii + 1, frame_count), end='', flush=True)
print('\n processing batch %d (%d->%d)...' % (bc,si,ei))
# shot detection - copy non-overlapping probs
temp = transnet_model.predict_frames(transnet_frames)
for i in range(cur_batch_len):
trans_probs.append(temp[batch_overlap+i])
# zero transnet_frames array
transnet_frames.fill(0)
# gather selected (non-skipped) frames
process_ind = -1
for i in range(cur_batch_len):
# check if we must process this frame
# force if:
# - force if frame after shot cut)
# - shot change
# - 1st frame of 1st batch
# - last frame
if ((si+i==true_inds[-1]+skip) if len(true_inds)>0 else True) or \
(after_shot_change) or \
(si+i==frame_count-1):
total_process_ind += 1
process_ind += 1
frames[process_ind] = frames[i]
true_inds.append(si+i)
trans_probs_sel.append(trans_probs[si+i])
if after_shot_change:
after_shot_change=False
after_shot_change = (trans_probs[si+i]>trans_threshold)
# register map index from
map2orig.append(total_process_ind)
# register shot_det time
sc_register_time(t, '_read_shot_det')
# set timer for "read_sal_det" time
t = cv2.getTickCount()
# comput start and end save indices for shot detection
ei = len(true_inds)-1
si = ei-process_ind
# resize saliency maps array if needed
if ei+1>=vid_data['smaps'].shape[2]:
if verbose:
print(' (resizing saliency map array:',vid_data['smaps'].shape, '->', end='')
vid_data['smaps'].resize((SAL_H, SAL_W, ei+100))
if verbose:
print(vid_data['smaps'].shape, ')')
# saliency detection
vid_data['smaps'][:,:,si:ei] = unisal_handler.predictions_from_memory_nuint8_np(unisal_model,
frames[:process_ind,:,:,:], [], '')
# zero frames array
frames.fill(0)
# register sal_det time
sc_register_time(t, '_read_sal_det')
# increment batch count
bc += 1
# reset current batch size
bsi = -1
# exit loop if this is the last batch we process
if bail_out:
break
# get true frame count (no frames that we successfully read)
true_frame_count = iii+1
# print time for init, open and reading of video
print(' done in %.3fs...'%((cv2.getTickCount() - t_total) / cv2.getTickFrequency()))
# start timer for "read_tidy" time
t = cv2.getTickCount()
# free video reader
fvs.stop()
del fvs
# free empty saliency maps at the end of the array
vid_data['smaps'] = vid_data['smaps'][:,:,:ei+1]
print(' gathered %d saliency maps...' % vid_data['smaps'].shape[2])
# infer segments from transition probs
vid_data['segmentation'] = predictions_to_scenes(np.array(trans_probs), threshold=trans_threshold)
# shot segmentation FIX
# make sure end of each segment is the start of next
# (original algorithm leaves black frame off)
for i in range(vid_data['segmentation'].shape[0]-1):
vid_data['segmentation'][i][1] = vid_data['segmentation'][i+1][0] - 1
vid_data['segmentation'][-1][1] = true_frame_count -1
# check for very small segments
### TODO
# infer segments for selected frames
vid_data['segmentation_sel'] = np.copy(vid_data['segmentation'])
for i in range(vid_data['segmentation_sel'].shape[0]):
for j in range(vid_data['segmentation_sel'].shape[1]):
vid_data['segmentation_sel'][i][j] = \
map2orig[vid_data['segmentation_sel'][i][j]]
# clean up
del trans_probs
del trans_probs_sel
# fill video data dictionary
vid_data['true_inds'] = true_inds
vid_data['inds_to_orig'] = map2orig
vid_data['fr'] = fr
vid_data['fc'] = true_frame_count
vid_data['fc_sel'] = vid_data['smaps'].shape[2]
vid_data['h_orig'] = h
vid_data['w_orig'] = w
vid_data['h_process'] = SAL_H
vid_data['w_process'] = SAL_W
# register sal_det time
sc_register_time(t, 'read_tidy')
# print info
if verbose:
print(' %-24s: %d'%('segmentation end', vid_data['segmentation'][-1][-1]))
print(' %-24s: %.3f'%('frame rate', vid_data['fr']))
print(' %-24s: %d'%('total frames', vid_data['fc']))
print(' %-24s: %d'%('true total frames', frame_count))
print(' %-24s: %d'%('selected frames', vid_data['fc_sel']))
print(' %-24s: %d'%('true indices len', len(vid_data['true_inds'])))
print(' %-24s: %d'%('map len', len(vid_data['inds_to_orig'])))
print(' %-24s: (%dx%d)'%('original dimension',vid_data['h_orig'],
vid_data['w_orig']))
print(' %-24s: (%dx%d)'%('process dimensions',vid_data['h_process'],
vid_data['w_process']))
print(' %-24s: (%dx%dx%d)'%('saliency shape',vid_data['smaps'].shape[0],
vid_data['smaps'].shape[1],
vid_data['smaps'].shape[2]))
print(' %-24s '%('segmentation'))
print(vid_data['segmentation'])
print(' %-24s '%('segmentation sel'))
print(vid_data['segmentation_sel'])
# sanity checks
all_good = True
if vid_data['fc']>frame_count:
print(' Error in sanity check (1)...')
all_good = False
if vid_data['fc_sel']!=len(vid_data['true_inds']):
print(' Error in sanity check (2)...')
all_good = False
if vid_data['fc']!=len(vid_data['inds_to_orig']):
print(' Error in sanity check (3)...')
all_good = False
if vid_data['fc_sel']!=vid_data['smaps'].shape[2]:
print(' Error in sanity check (4)...')
all_good = False
if vid_data['segmentation'][-1][-1]!=vid_data['fc']-1:
print(' Error in sanity check (5)...')
all_good = False
if vid_data['segmentation_sel'][-1][-1]!=vid_data['fc_sel']-1:
print(' Error in sanity check (6)...')
all_good = False
if vid_data['inds_to_orig'][-1]!=vid_data['fc_sel']-1:
print(' Error in sanity check (7)...')
all_good = False
if all_good and verbose:
print(' (sanity checks passed)')
if not all_good:
input('...')
# save times on video data dictionary
# to be available when re-loading video data
vid_data['times'] = {}
vid_data['times']['read_init'] = sc_get_time('read_init')
vid_data['times']['_read'] = sc_get_time('_read')
vid_data['times']['_read_shot_det'] = sc_get_time('_read_shot_det')
vid_data['times']['_read_sal_det'] = sc_get_time('_read_sal_det')
vid_data['times']['read_tidy'] = sc_get_time('read_tidy')
return vid_data
# Reads a video, performs shot and saliency detection
# return segmentation info and samples saliency mapsd
def ingest_pickle(pickle_path, crop_params, verbose=False):
t_total = cv2.getTickCount()
# open pickle and get data
print(' ingesting %s...' % pickle_path)
with open(pickle_path, 'rb') as fpsc:
x = pickle.load(fpsc)
print(x.keys())
fr = x['fr']
frame_count =x['frame_count']
w = x['w']
h = x['h']
original_frames = x['frames'] # must be in RGB
trans_inds = x['trans_inds']
# compute batch size based on frame rate
batch_size = crop_params['read_batch']
batch_overlap = int(fr)
# compute frames size for saliency detection
dsr = float(max(w,h)) / crop_params['max_input_d']
SAL_H = int(h/dsr)
SAL_W = int(w/dsr)
# init an array to hold the resized frames for
# saliency detection
frames = np.zeros((batch_size,
SAL_H, SAL_W, 3),
dtype=np.uint8)
# init video data dictionary
vid_data = {}
# estimate number of frames taking into account skipped onew
fcs = 0
skip = crop_params['skip']
for i in range(frame_count):
if (i%skip==0) or (i==0) or i==(frame_count-1):
fcs += 1
fcs += int(frame_count*0.1)
if verbose:
print(' (estimating %d sal. maps)' % fcs)
# init an array to hold saliency maps
vid_data['smaps'] = np.zeros((SAL_H, SAL_W, fcs),
dtype=np.uint8)
# init a list to hold true indices of processed frames
true_inds = [] # in=sampled frame index, out=respective true frame index
map2orig = [] # in=true frame index, out=respective sampled frame index
# init current batch size and batch count
bc = 0
bsi = -1
total_process_ind = -1
# register read_init time
sc_register_time(t_total, 'read_init')
# loop through video
after_shot_change = False
for iii,frame in enumerate(original_frames):
# set timer for "read" time
t = cv2.getTickCount()
# show header and try to load frame
if (iii%50==0) or (iii>frame_count-50):
print('\r reading %d/%d ' % (iii+1, frame_count), end='', flush=True)
# increment count of frames in batch
bsi += 1
# register frame for shot segmentation
frames[bsi,:,:,:] = cv2.resize(frame,
(SAL_W, SAL_H),
interpolation=cv2.INTER_LINEAR)
# compute current batch
cur_batch_len = bsi+1
# register read time
sc_register_time(t, '_read')
# process frames if we have a complete or the last batch
if cur_batch_len==batch_size or iii+1==len(original_frames):
# if new batch is empty break
if cur_batch_len==0:
break
# set timer for "read_shot_det" time
t = cv2.getTickCount()
# comput start and end save indices for shot detection
si = bc*batch_size
ei = si+cur_batch_len
# print info
print('\r reading %d/%d ' % (iii + 1, frame_count), end='', flush=True)
print('\n processing batch %d (%d->%d)...' % (bc,si,ei))
# gather selected (non-skipped) frames
process_ind = -1
for i in range(cur_batch_len):
# check if we must process this frame
# force if:
# - force if frame after shot cut)
# - shot change
# - 1st frame of 1st batch
# - last frame
if ((si+i==true_inds[-1]+skip) if len(true_inds)>0 else True) or \
(after_shot_change) or \
(si+i==frame_count-1):
total_process_ind += 1
process_ind += 1
frames[process_ind] = frames[i]
true_inds.append(si+i)
if after_shot_change:
after_shot_change=False
# check if frame is after a shot change
if i-1 in trans_inds:
after_shot_change=True
# register map index from
map2orig.append(total_process_ind)
# register shot_det time
sc_register_time(t, '_read_shot_det')
# set timer for "read_sal_det" time
t = cv2.getTickCount()
# comput start and end save indices for shot detection
ei = len(true_inds)-1
si = ei-process_ind
# resize saliency maps array if needed
if ei+1>=vid_data['smaps'].shape[2]:
if verbose:
print(' (resizing saliency map array:',vid_data['smaps'].shape, '->', end='')
vid_data['smaps'].resize((SAL_H, SAL_W, ei+100))
if verbose:
print(vid_data['smaps'].shape, ')')
# saliency detection
vid_data['smaps'][:,:,si:ei] = unisal_handler.predictions_from_memory_nuint8_np(unisal_model,
frames[:process_ind,:,:,:], [], '')
# register sal_det time
sc_register_time(t, '_read_sal_det')
# increment batch count
bc += 1
# reset current batch size
bsi = -1
# clear frames read from the pickle file and loaded pickle file
del original_frames
del x
# get true frame count (no frames that we successfully read)
true_frame_count = iii+1
# print time for init, open and reading of video
print(' done in %.3fs...'%((cv2.getTickCount() - t_total) / cv2.getTickFrequency()))
# start timer for "read_tidy" time
t = cv2.getTickCount()
# free empty saliency maps at the end of the array
vid_data['smaps'] = vid_data['smaps'][:,:,:ei+1]
print(' gathered %d saliency maps...' % vid_data['smaps'].shape[2])
# infer segments from transition probs
# shot segmentation FIX not needed because segmentation comes from summary segments
print(trans_inds)
scenes=[]
for i in range(len(trans_inds)):
if frame_count-trans_inds[i]<2:
break
if i+1<len(trans_inds):
scenes.append([trans_inds[i], trans_inds[i+1]-1])
vid_data['segmentation'] = np.array(scenes, dtype=np.int32)
print(vid_data['segmentation'])
# check for very small segments
### TODO
# infer segments for selected frames
vid_data['segmentation_sel'] = np.copy(vid_data['segmentation'])
for i in range(vid_data['segmentation_sel'].shape[0]):
for j in range(vid_data['segmentation_sel'].shape[1]):
vid_data['segmentation_sel'][i][j] = \
map2orig[vid_data['segmentation_sel'][i][j]]
# fill video data dictionary
vid_data['true_inds'] = true_inds
vid_data['inds_to_orig'] = map2orig
vid_data['fr'] = fr
vid_data['fc'] = true_frame_count
vid_data['fc_sel'] = vid_data['smaps'].shape[2]
vid_data['h_orig'] = h
vid_data['w_orig'] = w
vid_data['h_process'] = SAL_H
vid_data['w_process'] = SAL_W
# register sal_det time
sc_register_time(t, 'read_tidy')
# print info
if verbose:
print(' %-24s: %d'%('segmentation end', vid_data['segmentation'][-1][-1]))
print(' %-24s: %.3f'%('frame rate', vid_data['fr']))
print(' %-24s: %d'%('total frames', vid_data['fc']))
print(' %-24s: %d'%('true total frames', frame_count))
print(' %-24s: %d'%('selected frames', vid_data['fc_sel']))
print(' %-24s: %d'%('true indices len', len(vid_data['true_inds'])))
print(' %-24s: %d'%('map len', len(vid_data['inds_to_orig'])))
print(' %-24s: (%dx%d)'%('original dimension',vid_data['h_orig'],
vid_data['w_orig']))
print(' %-24s: (%dx%d)'%('process dimensions',vid_data['h_process'],
vid_data['w_process']))
print(' %-24s: (%dx%dx%d)'%('saliency shape',vid_data['smaps'].shape[0],
vid_data['smaps'].shape[1],
vid_data['smaps'].shape[2]))
print(' %-24s '%('segmentation'))
print(vid_data['segmentation'])
print(' %-24s '%('segmentation sel'))
print(vid_data['segmentation_sel'])
# sanity checks
all_good = True
if vid_data['fc']>frame_count:
print(' Error in sanity check (1)...')
all_good = False
if vid_data['fc_sel']!=len(vid_data['true_inds']):
print(' Error in sanity check (2)...')
all_good = False
if vid_data['fc']!=len(vid_data['inds_to_orig']):
print(' Error in sanity check (3)...')
all_good = False
if vid_data['fc_sel']!=vid_data['smaps'].shape[2]:
print(' Error in sanity check (4)...')
all_good = False
if vid_data['segmentation'][-1][-1]!=vid_data['fc']-1:
print(' Error in sanity check (5)...')
all_good = False
if vid_data['segmentation_sel'][-1][-1]!=vid_data['fc_sel']-1:
print(' Error in sanity check (6)...')
all_good = False
if vid_data['inds_to_orig'][-1]!=vid_data['fc_sel']-1:
print(' Error in sanity check (7)...')
all_good = False
if all_good and verbose:
print(' (sanity checks passed)')
if not all_good:
input('...')
# save times on video data dictionary
# to be available when re-loading video data
vid_data['times'] = {}
vid_data['times']['read_init'] = sc_get_time('read_init')
vid_data['times']['_read'] = sc_get_time('_read')
vid_data['times']['_read_shot_det'] = sc_get_time('_read_shot_det')
vid_data['times']['_read_sal_det'] = sc_get_time('_read_sal_det')
vid_data['times']['read_tidy'] = sc_get_time('read_tidy')
return vid_data
# Checks for blank borders in the video frames
# computes the dimensions to cut
def sc_border_detection(crop_params, vid_data, verbose=False):
if crop_params['t_border']==-1:
# if border detection is off set all border to zero
vid_data['border_t'] = 0
vid_data['border_b'] = 0
vid_data['border_l'] = 0
vid_data['border_r'] = 0
return vid_data
# alias process dimensions for quick reference
h = vid_data['h_process']
w = vid_data['w_process']
ho = vid_data['h_orig']
wo = vid_data['w_orig']
# get min across time (3d to 2d)
sal_max = np.max(vid_data['smaps'], axis=2)
# get max across rows (2d to column)
f_col = np.max(sal_max, axis=1)
# get max acroos cols (2d to row)
f_row = np.max(sal_max, axis=0)
# print info
if verbose:
np.set_printoptions(edgeitems=10)
print(' column max sal (top-botom borders) (%d):\n'%len(f_col), f_col)
print(' row max sal (left and right borders) (%d):\n'%len(f_row), f_row)
np.set_printoptions(edgeitems=3)
# compute top and bottom borders
t = 0
for i in range(h):
if f_col[i] > crop_params['t_border']:
break
t += 1
b = 0
for i in range(h):
if f_col[-(i + 1)] > crop_params['t_border']:
break
b += 1
# compute left and right borders
l = 0
for i in range(w):
if f_row[i] > crop_params['t_border']:
break
l += 1
r = 0
for i in range(w):
if f_row[-(i + 1)] > crop_params['t_border']:
break
r += 1
# register limited borders w.r.t final crop window dims and a max border
if True:
vid_data['border_t'] = min(t, int(h*0.45))
vid_data['border_b'] = min(b, int(h*0.45))
vid_data['border_l'] = min(l, int(w*0.45))
vid_data['border_r'] = min(r, int(w*0.45))
else:
vid_data['border_t'] = t
vid_data['border_b'] = b
vid_data['border_l'] = l
vid_data['border_r'] = r
# borders will be use when considering original dimensions
# scale back to original
vid_data['border_t'] = int((ho/h)*vid_data['border_t'])
vid_data['border_b'] = int((ho/h)*vid_data['border_b'])
vid_data['border_l'] = int((wo/w)*vid_data['border_l'])
vid_data['border_r'] = int((wo/w)*vid_data['border_r'])
if verbose:
print(' %-24s: (%dx%d) t=%d,b=%d,l=%d,r=%d' % ('border detection',
ho,wo,
vid_data['border_t'] ,
vid_data['border_b'] ,
vid_data['border_l'] ,
vid_data['border_r'] ))
return vid_data
# Computes the IoU of two rectangles
def bb_intersection_over_union(boxA, boxB):
# determine the (x, y)-coordinates of the intersection rectangle
xA = max(boxA[0], boxB[0])
yA = max(boxA[1], boxB[1])
xB = min(boxA[2], boxB[2])
yB = min(boxA[3], boxB[3])
# compute the area of intersection rectangle
interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)
# compute the area of both the prediction and ground-truth
# rectangles
boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)
boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)
# compute the intersection over union by taking the intersection
# area and dividing it by the sum of prediction + ground-truth
# areas - the interesection area
iou = interArea / float(boxAArea + boxBArea - interArea)
# return the intersection over union value
return iou
def sc_calc_dest_size(vid_data, crop_params, verbose=True):
orig_w_units = vid_data['w_orig']
orig_h_units = vid_data['h_orig']
orig_ratio = float(orig_w_units)/float(orig_h_units)
c = crop_params['out_ratio'].split(':')
target_w_units = float(c[0])
target_h_units = float(c[1])
target_ratio = float(target_w_units)/float(target_h_units)
# check cases for setting conversion mode
if abs(orig_ratio-target_ratio)<0.0000001:
vid_data['conversion_mode'] = 0
print(' (no conversion)')
vid_data['w_final'] = vid_data['w_orig']
vid_data['h_final'] = vid_data['h_orig']
else:
vid_data['w_final'] = int(math.floor((target_w_units/target_h_units) * vid_data['h_orig']))
vid_data['h_final'] = vid_data['h_orig']
vid_data['conversion_mode'] = 1
if vid_data['w_final']>vid_data['w_orig'] or vid_data['h_final']>vid_data['h_orig']:
vid_data['w_final'] = vid_data['w_orig']
vid_data['h_final'] = int(math.floor((target_h_units/target_w_units) * vid_data['w_orig']))
vid_data['conversion_mode'] = 2
print(' preserving width')
else:
print(' preserving height')
if verbose:
print(' orig. (hxw): (%dx%d)' % (vid_data['h_orig'], vid_data['w_orig']))
print(' final (hxw): (%dx%d)' % (vid_data['h_final'], vid_data['w_final']))
return vid_data
def sc_compute_bb(vid_data, crop_params, verbose=False):
# alias parameters of quick reference
frame_h = vid_data['h_orig']
frame_w = vid_data['w_orig']
process_h = vid_data['h_process']
process_w = vid_data['w_process']
scale_h = float(process_h) / float(frame_h)
scale_w = float(process_w) / float(frame_w)
bb_h = vid_data['h_final']
bb_w = vid_data['w_final']
bt = vid_data['border_t']
bb = vid_data['border_b']
bl = vid_data['border_l']
br = vid_data['border_r']
# scale center coordinates back to original dimensions
final_xs = vid_data['dxs']
final_ys = vid_data['dys']
for i in range(vid_data['fc']):
final_xs[i] = int(final_xs[i] / scale_w)
final_ys[i] = int(final_ys[i] / scale_h)