-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpulsecam_iccv6.py
2323 lines (1951 loc) · 61.1 KB
/
pulsecam_iccv6.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 serial
import argparse
import cv2
import flycapture2 as fc2
import tensorflow as tf
import numpy as np
import scipy.misc
import scipy.signal
import pickle
import json
import os, glob
import math
import copy
from utils import *
import time
#notes
# -did I mix up x and y again? always worth checking
#debugging
import pdb
#multithreading
import threading
displayThread = threading.Condition()
I_cache = 0
I_idx = 0 # update idx
outside_I = 0
results = 0
ending_key = 'c'
robust_mode = 'scanner_starter'
#the range for different outputs, range set to NaN means auto-ranging
DEPTH_RANGE = [-1.0,-0.3]#[-1.0,-0.3] # -1.0,-0.5
DEPTH_RANGE_f = [-3.0,-0.3]#[-1.0,-0.3] # -1.0,-0.5
FONT = cv2.FONT_HERSHEY_DUPLEX
KEY_RANGE = {
'raw' : [0,255],
'gray' : [0,255],
'test' : [0,255],
'I_0' : [0,255],
'I_1' : [0,255],
'I_2' : [0,255],
'Z' : DEPTH_RANGE,
'Zf' : DEPTH_RANGE,
'Z_crop' : DEPTH_RANGE,
'Z_cropdZdu' : DEPTH_RANGE,
'Z_cropw' : DEPTH_RANGE,
'estUnc' : [-99999999,3],
}
KEYS_TO_TILE = ['ATA', 'ATA^-1', 'ATb', 'U']
class OutsideCamera(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.cfg = {
#processing configuration knobs
'wrapper': 'opencv', # Select the wrapper
'downscale': 1, #downscaling of the image
'camera' : 0, #the integer mapping to the camera you
#want to use. typically 0, but depends on what's available
'input_video' : None, #file name for a video file to
#use for debugging. Will just loop through. Can also
#use something like "path-to-images/%2d.tif" as the
#input here, that will show through all the images
#that match that string.
}
self.t = []
self.draw = None
self.cache = {}
self.vars = {}
self.frames = 0
self.resolution = None
#initialize camera
self.cam = None
self.initialize_camera_opencv()
#initialize cache
for k in ['gray']:
self.cache[k] = np.zeros(self.resolution)
self.outside_I = np.zeros(self.resolution, dtype = np.uint8)
def run(self):
global ending_key
# The code to capture images
t0 = time.time()
while True:
self.t0 = time.time()
self.grab_frame_and_process_opencv()
# obtain the input
displayThread.acquire()
c = cv2.waitKey(1) & 0xFF
displayThread.release()
if c != 255:
ending_key = chr(c).lower()
if ending_key == 'q':
print("quitting")
self.final_statistics()
break
self.t.append(time.time()-self.t0)
self.frames += 1
# display frame rate in real time
if np.mod(self.frames,1000)==0:
t1 = time.time()
perf = (1.0*self.frames)/(t1-t0)
print("outside camera frame rate: (gross speed)", perf, " fps")
def initialize_camera_opencv(self):
#open camera using opencv wrapper
self.cfg['cam_src'] = self.cfg['camera']
if self.cfg['input_video'] is not None:
self.cfg['cam_src'] = self.cfg['input_video']
self.cam = cv2.VideoCapture(self.cfg['cam_src'])
if not self.cam.isOpened():
raise Exception("Could not open camera %s"%str(self.cfg['cam_src']))
ry = int(self.cam.get(cv2.CAP_PROP_FRAME_HEIGHT))
rx = int(self.cam.get(cv2.CAP_PROP_FRAME_WIDTH))
if self.cfg['downscale'] != 1:
self.cam.set(cv2.CAP_PROP_FRAME_HEIGHT, ry/self.cfg['downscale'])
self.cam.set(cv2.CAP_PROP_FRAME_WIDTH, rx/self.cfg['downscale'])
ry = int(self.cam.get(cv2.CAP_PROP_FRAME_HEIGHT))
rx = int(self.cam.get(cv2.CAP_PROP_FRAME_WIDTH))
self.resolution = [ry, rx]
#try to run at least at 60 fps
self.cam.set(cv2.CAP_PROP_FPS, 16)
self.cfg['camera_fps'] = self.cam.get(cv2.CAP_PROP_FPS)
def grab_frame_and_process_opencv(self):
# Using the opencv camera
r, raw = self.cam.read()
if not r:
if self.cfg['input_video'] is not None:
self.cam = cv2.VideoCapture(self.cfg['cam_src'])
r, raw = self.cam.read()
else:
raise Exception("Could not get image from camera '%s'"%str(self.cfg['cam_src']))
return self.process(raw)
"""imports a frame into """
def process(self, new_frame):
# Define the global variables
global outside_I
self.cache['raw'] = new_frame
if len(new_frame.shape) > 2:
# or new_frame.shape[2] != 1:
self.cache['gray'] = cv2.cvtColor(self.cache['raw'], cv2.COLOR_BGR2GRAY)
else:
self.cache['gray'] = self.cache['raw'].copy()
self.outside_I = self.cache['gray'][150:300,170:-30:]
# Lock the global variables, to updates those images
outside_I = self.outside_I
self.frames += 1
return
"""computes the average FPS over the last __FPS_WINDOW frames"""
def get_fps(self):
__FPS_WINDOW = 4
if len(self.t) < __FPS_WINDOW:
return -1
else:
return __FPS_WINDOW/(1.0*sum(self.t[-1:-1 - __FPS_WINDOW:-1]))
"""computes some performance statistics at the end"""
def final_statistics(self):
if len(self.t) < 2:
print("too short, invalid statistics...")
return
t = np.array(self.t)
fps = 1.0/t;
print("""
#####################################
### OUTSIDE CAMERA FPS STATISTICS ###
#####################################
min: %(min)f
med: %(median)f
avg: %(avg)f
max: %(max)f
#####################################
"""%{'min':fps.min(), 'avg':fps.mean(), 'median': np.median(fps), 'max': fps.max()})
def regular_output(self):
self.cache['draw'] = tile_image(\
I = [self.outside_I.astype(np.float32)], \
rng = [KEY_RANGE['raw']], \
log = False, \
title = "Outside Camera", \
)
cv2.imshow("Outside Camera", self.cache['draw'])
"""destructor: free up resources when done"""
def __del__(self):
if self.cam is not None:
self.cam.release()
self.cam = None
#TODO video writer stuff here
cv2.destroyAllWindows()
class Camera(threading.Thread):
"""A class for the camera"""
def __init__(self):
threading.Thread.__init__(self)
#default configuraiton
self.cfg = {
#processing configuration knobs
'wrapper': 'ptg', # Select the wrapper
'downscale': 2, #downscaling of the image
'camera' : 0, #the integer mapping to the camera you
#want to use. typically 0, but depends on what's available
'input_video' : None, #file name for a video file to
#use for debugging. Will just loop through. Can also
#use something like "path-to-images/%2d.tif" as the
#input here, that will show through all the images
#that match that string.
}
self.t = []
self.t0 = 0
self.draw = None
self.cache = {}
self.vars = {}
self.frames = 0
self.resolution = None
#initialize camera
self.cam = None
self.initialize_camera_ptg()
#initialize cache
for k in ['gray']:
self.cache[k] = np.zeros(self.resolution)
#initialize computation
self.Z_t = []
self.sample_images = None
self.data_type = tf.float32
self.I_cache = np.zeros(self.resolution+(2,), dtype = np.uint8)
self.time_lapse = 0
def run(self):
global ending_key
# The code to capture images
t0 = time.time()
while True:
if self.t0 != 0:
t1 = time.time()
self.time_lapse = t1 - self.t0
self.t0 = t1
else:
self.t0 = time.time()
self.grab_frame_and_process_ptg()
# self.regular_output()
# obtain the input
displayThread.acquire()
c = cv2.waitKey(1) & 0xFF
displayThread.release()
if c != 255:
ending_key = chr(c).lower()
if ending_key == 'q':
print("quitting")
self.final_statistics()
break
self.t.append(time.time()-self.t0)
# display frame rate in real time
if np.mod(self.frames,1000)==0:
t1 = time.time()
perf = (1.0*self.frames)/(t1-t0)
print("camera capture frame rate: (gross speed)", perf, " fps")
def initialize_camera_ptg(self):
#access the point grey camera using flycap
print(fc2.get_library_version())
self.ptg = fc2.Context()
print(self.ptg.get_num_of_cameras())
self.ptg.connect(*self.ptg.get_camera_from_index(0))
print(self.ptg.get_camera_info())
m, f = self.ptg.get_video_mode_and_frame_rate()
print(m, f)
# print(c.get_video_mode_and_frame_rate_info(m, f))
print(self.ptg.get_property_info(fc2.FRAME_RATE))
p = self.ptg.get_property(fc2.FRAME_RATE)
print(p)
self.ptg.set_property(**p)
self.ptg.start_capture()
self.im = fc2.Image()
# try to get the first image to
print([np.array(self.ptg.retrieve_buffer(self.im)).sum() for i in range(80)])
img = np.array(self.im)
print(img.shape, img.base)
# downscaling the images
img = scipy.misc.imresize(img, 1/self.cfg['downscale'])
self.resolution = (
img.shape[0],img.shape[1]
)
self.cfg['camera_fps'] = p['abs_value']
def decide_idx(self, new_image):
global I_idx
# try to find out which image should be replaced
err = np.zeros((self.I_cache.shape[2]))
for i in range(self.I_cache.shape[2]):
err[i] = np.mean(np.abs(self.I_cache[:,:,i] - new_image))
I_idx = np.argmin(err)
return
def naive_idx(self):
global I_idx
I_idx = 1 - I_idx
return
"""imports a frame into """
def process(self, new_frame):
# Define the global variables
global I_cache
self.cache['raw'] = new_frame
if len(new_frame.shape) > 2:
# or new_frame.shape[2] != 1:
self.cache['gray'] = cv2.cvtColor(self.cache['raw'], cv2.COLOR_BGR2GRAY)
else:
self.cache['gray'] = self.cache['raw'].copy()
# # decide which idx of image should be updated
# if self.frames > 2:
# self.decide_idx(self.cache['gray'])
# else:
# self.naive_idx()
# if self.time_lapse > 0.02:
# # if the time is above threshold, we think it miss one frame
# print("Time lapse (s): ", self.time_lapse)
# else:
# self.naive_idx()
self.naive_idx()
# self.decide_image()
self.I_cache[:,:,I_idx] = self.cache['gray']
# Lock the global variables, to updates those images
I_cache = self.I_cache
self.frames += 1
return
def decide_image(self):
err = [\
np.mean(\
np.abs(\
self.cache['gray'].astype(np.float32)-\
self.I_cache[:,:,0].astype(np.float32)
)
),
np.mean(\
np.abs(\
self.cache['gray'].astype(np.float32)-\
self.I_cache[:,:,1].astype(np.float32)
)
)
]
if err[0] < err[1]:
idx = 0
else:
idx = 1
if idx != I_idx:
print("Switching Time lapse: ", self.time_lapse, err, I_idx, self.frames, )
print(np.mean(self.cache['gray']),np.mean(self.I_cache[:,:,0]),\
np.mean(self.I_cache[:,:,1]))
"""helper: grabs the frame and runs the processing stage"""
def grab_frame_and_process_ptg(self):
# Using the point grey camera
self.ptg.retrieve_buffer(self.im)
img = np.array(self.im)
img = scipy.misc.imresize(img, 1/self.cfg['downscale'])
return self.process(img)
"""computes the average FPS over the last __FPS_WINDOW frames"""
def get_fps(self):
__FPS_WINDOW = 4
if len(self.t) < __FPS_WINDOW:
return -1
else:
return __FPS_WINDOW/(1.0*sum(self.t[-1:-1 - __FPS_WINDOW:-1]))
"""computes some performance statistics at the end"""
def final_statistics(self):
if len(self.t) < 2:
print("too short, invalid statistics...")
return
t = np.array(self.t)
fps = 1.0/t;
print("""
#####################################
### CAMERA CAPTURE FPS STATISTICS ###
#####################################
min: %(min)f
med: %(median)f
avg: %(avg)f
max: %(max)f
#####################################
"""%{'min':fps.min(), 'avg':fps.mean(), 'median': np.median(fps), 'max': fps.max()})
def regular_output(self):
self.cache['draw'] = tile_image(\
I = [self.I_cache[:,:,0].astype(np.float32),\
self.I_cache[:,:,1].astype(np.float32)], \
rng = [KEY_RANGE['raw'], KEY_RANGE['raw']], \
log = False, \
title = "Camera Thread", \
)
cv2.imshow("Camera Thread", self.cache['draw'])
"""destructor: free up resources when done"""
def __del__(self):
#TODO video writer stuff here
cv2.destroyAllWindows()
class PulseCamProcessorTF(threading.Thread):
"""constructor: initializes FocalFlowProcessor"""
def __init__(self, cfg, cfgf):
threading.Thread.__init__(self)
self.cfg = cfg
self.cfgf = cfgf
# resolution
self.resolution = []
for i in range(len(self.cfg)):
self.resolution.append(
(
self.cfg[i]['szy_sensor'],
self.cfg[i]['szx_sensor']
)
)
self.cfg[i]['P'] = 1/self.cfg[i]['f']
# # update the old parameters
# keys = ['a0a1','b0','b1','w_bc','w_bc1','w_bc2']
# for key in keys:
# for i in range(len(self.cfg)):
# self.cfg[i][key] = self.cfgf[i][key]
self.required_outs = ['Z']
self.vars_to_fuse = ['Z','conf','u_2']
self.input_dict = {}
# variables
self.vars = []
self.vars_align = {}
self.vars_fuse = {}
self.t = []
self.draw = None
self.cache = {}
self.vars = []
self.frames = 0
self.frames_track = 0
#initialize computation
self.Z_t = []
self.results = {}
# the port
self.Z_tgt = self.cfg[0]['a1']
self.Z_tgt0 = self.cfg[0]['a1']
for i in range(len(self.cfg)):
self.cfg[i]['a0a1'] = self.cfg[i]['a0'] * self.cfg[0]['a1']
self.offset_range = [30000,55000]
self.inte = 0
self.prev_err = 0
self.offset = int((1/self.Z_tgt + 1.9)*1e4)
if self.offset < self.offset_range[0]:
self.offset = self.offset_range[0]
elif self.offset > self.offset_range[1]:
self.offset = self.offset_range[1]
print("offset: ", self.offset)
self.ser = serial.Serial()
self.ser.port = "/dev/ttyUSB0" # may be called something different
self.ser.baudrate = 9600 # may be different
self.ser.open()
# initialize the lens
if self.ser.isOpen():
string = "OF"+str(self.offset)+";"
self.ser.write(string.encode())
response = self.ser.read(self.ser.inWaiting())
# we initialize with the tracking method to be passive
self.track_methods = ['track_Z_pid']
self.track_idx = 0
self.robust_mode = 'scanner_starter'
# tf graph
self.graph = tf.Graph()
self.session = tf.Session(graph = self.graph)
self.data_type = tf.float32
# save the data from the camera
self.I_cache = np.zeros(self.resolution[0]+(2,), dtype = np.uint8)
# save the old data to keep the sequence
self.old_data = {}
self.old_num = 3
self.old_idx = 0
self.old_data['Z'] = [[] for i in range(self.old_num)]
self.old_data['conf'] = [[] for i in range(self.old_num)]
# make a video recorder
self.build_graph()
def run(self):
global ending_key
t0 = time.time()
while True:
self.t0 = time.time()
self.process()
self.robust_track_Z()
# obtain the input
displayThread.acquire()
c = cv2.waitKey(1) & 0xFF
displayThread.release()
if c != 255:
ending_key = chr(c).lower()
# quit
if ending_key == 'q':
print("quitting")
self.final_statistics()
break
# reset to the scanner
if ending_key == 'r':
self.robust_mode = 'scanner_starter'
self.frames += 1
self.frames_track += 1
self.t.append(time.time()-self.t0)
# display frame rate in real time
if np.mod(self.frames,1000)==0:
t1 = time.time()
perf = (1.0*self.frames)/(t1-t0)
print("FT avg performance: (gross speed)", perf, " fps")
"""describes the computations (graph) to run later
-make all algorithmic changes here
-note that tensorflow has a lot of support for backpropagation
gradient descent/training, so you can build another part of the
graph that computes and updates weights here as well.
"""
def build_graph(self):
with self.graph.as_default():
# initialization of all variables
I_init = np.zeros(
self.resolution[0]+(self.cfg[0]['ft'].shape[2],),
dtype = np.float32
)
self.I_in = tf.Variable(I_init)
I = tf.Variable(I_init)
self.a1_in = tf.Variable(1, dtype=tf.float32)
a1 = tf.Variable(1, dtype=tf.float32)
self.offset_in = tf.Variable(1, dtype=tf.float32)
offset = tf.Variable(1, dtype=tf.float32)
I_batch = []
I_lap_batch = []
Z_0 = []
a0a1 = []
a0 = []
ra0_1 = []
ra0_2 = []
ra1_1 = []
ra1_2 = []
Z_0f = []
a0f_o = []
a1f_o = []
a0f = []
a1f = []
gauss = []
ext_f = []
ft = []
fave = []
I_t = []
I_lap = []
u_1 = []
u_2 = []
u_3 = []
u_4 = []
u_2f = []
u_3f = []
u_4f = []
# depth computation
# I used to be (960, 600, 2or 3) we change it to (2or3, 960, 600)
tmp_I = tf.stack(\
[dIdt(I, self.cfg[0]['ft']), \
dIdt(I, self.cfg[0]['fave'])]
)
# tmp_I = tf.transpose(I, perm=[2,0,1])
for i in range(len(self.cfg)):
# initialize variables
"""Input parameters"""
Z_0.append(tf.constant(self.cfg[i]['Z_0'], dtype = tf.float32))
a0a1.append(tf.constant(self.cfg[i]['a0a1'], dtype = tf.float32))
a0.append(a0a1[i]/a1)
Z_0f.append(tf.constant(self.cfgf[i]['Z_0'], dtype= tf.float32))
# compute a0
a0f_o.append(tf.constant(self.cfgf[i]['a0_o'], dtype = tf.float32))
a1f_o.append(tf.constant(self.cfgf[0]['a1_o'], dtype = tf.float32))
o = tf.stack([(offset/10000)**k for k in range(len(self.cfgf[i]['a0_o']))],0)
a0f.append(tf.reduce_sum(o*a0f_o[i]))
a1f.append(tf.reduce_sum(o*a1f_o[i]))
# radial distortion
xx,yy = np.meshgrid(\
np.arange(self.resolution[i][1]),
np.arange(self.resolution[i][0])
)
xx = (xx - (self.resolution[i][1]-1)/2)/self.resolution[i][0]
yy = (yy - (self.resolution[i][0]-1)/2)/self.resolution[i][0] * 0.001
rr = np.sqrt(xx**2 + yy**2)
r = tf.constant(rr, dtype=tf.float32)
ra0_1.append(tf.Variable(self.cfgf[i]['ra0_1'], dtype=tf.float32))
ra0_2.append(tf.Variable(self.cfgf[i]['ra0_2'], dtype=tf.float32))
ra1_1.append(tf.Variable(self.cfgf[i]['ra1_1'], dtype=tf.float32))
ra1_2.append(tf.Variable(self.cfgf[i]['ra1_2'], dtype=tf.float32))
# pdb.set_trace()
a0f_r = a0f[i] + ra0_1[i] * r + ra0_2[i] * (r**2)
a1f_r = a1f[i] + ra1_1[0] * r + ra1_2[0] * (r**2)
gauss.append(tf.constant(self.cfg[i]['gauss'], dtype = tf.float32))
ext_f.append(tf.constant(self.cfg[i]['ext_f'], dtype = tf.float32))
ft.append(tf.constant(self.cfg[i]['ft'], dtype = tf.float32))
fave.append(tf.constant(self.cfg[i]['fave'], dtype = tf.float32))
# multi resolution
I_t.append(tmp_I[0,:,:])
tmp_I_blur = dIdx_batch(tmp_I, gauss[i])
I_lap.append(tmp_I[1,:,:] - tmp_I_blur[1,:,:])
if i < len(self.cfg)-1:
tmp_I = tf.squeeze(\
tf.image.resize_bilinear(\
tf.expand_dims(
tmp_I_blur,-1
),
self.resolution[i+1],
align_corners = True
),[-1]
)
# unwindowed version
u_1.append(I_lap[i])
u_2.append(I_t[i])
u_3.append(a0[i] * a1 * u_1[i])
u_4.append(-u_2[i] + a0[i] * u_1[i] + 1e-5)
u_3f.append(a0f_r * a1f_r * u_1[i])
u_4f.append(-u_2[i] + a0f_r * u_1[i] + 1e-5)
ext_f[i] = tf.expand_dims(\
tf.transpose(ext_f[i], perm=[1,2,0]),-2
)
u_2[i] = tf.expand_dims(tf.expand_dims(u_2[i],0),-1)
u_3[i] = tf.expand_dims(tf.expand_dims(u_3[i],0),-1)
u_4[i] = tf.expand_dims(tf.expand_dims(u_4[i],0),-1)
u_3f[i] = tf.expand_dims(tf.expand_dims(u_3f[i],0),-1)
u_4f[i] = tf.expand_dims(tf.expand_dims(u_4f[i],0),-1)
u_2[i] = tf.nn.conv2d(u_2[i], ext_f[i],[1,1,1,1],padding='SAME')[0,:,:,:]
u_2f.append(u_2[i])
u_3[i] = tf.nn.conv2d(u_3[i], ext_f[i],[1,1,1,1],padding='SAME')[0,:,:,:]
u_4[i] = tf.nn.conv2d(u_4[i], ext_f[i],[1,1,1,1],padding='SAME')[0,:,:,:]
u_3f[i] = tf.nn.conv2d(u_3f[i], ext_f[i],[1,1,1,1],padding='SAME')[0,:,:,:]
u_4f[i] = tf.nn.conv2d(u_4f[i], ext_f[i],[1,1,1,1],padding='SAME')[0,:,:,:]
#save references to required I/O]
self.vars.append({})
# self.vars[i]['I'] = I_batch[i]
# unwindowed version
self.vars[i]['u_1'] = u_1[i]
self.vars[i]['u_2'] = u_2[i]
self.vars[i]['u_2f'] = u_2f[i]
self.vars[i]['u_3'] = u_3[i]
self.vars[i]['u_4'] = u_4[i]
self.vars[i]['u_3f']= u_3f[i]
self.vars[i]['u_4f']= u_4f[i]
# align depth and confidence maps
self.align_maps_ext(['u_2','u_2f','u_3','u_4','u_3f','u_4f'])
# flatten the u_3, u_4, u_4f to enable faster computation
for key in ['u_2','u_2f','u_3','u_4','u_3f','u_4f']:
self.vars_align[key] = tf.reshape(\
self.vars_align[key],
[-1, len(self.cfg)*self.cfg[0]['ext_f'].shape[0]]
)
# compute the aligned version of Z
self.vars_align['Z'] = \
self.vars_align['u_3'] / (self.vars_align['u_4'] + 1e-5) + Z_0[0]
self.vars_align['Zf'] = \
self.vars_align['u_3f'] / (self.vars_align['u_4f']+ 1e-5) + Z_0f[0]
# compute windowed and unwindowed confidence
eval('self.'+self.cfg[0]['conf_func']+'()')
# fusion
self.softmax_fusion()
# averaging the confidence to remove noise
conf_ave = tf.stack(\
[self.vars_fuse['conf'],self.vars_fuse['conff']]
)
conf_ave = dIdx_batch(conf_ave, gauss[0])
# threshold the confidence by I_t
flag = tf.cast(tf.less(10., self.vars_fuse['u_2']), tf.float32)
self.vars_fuse['conf'] = conf_ave[0,:,:] #* flag
self.vars_fuse['conff'] = conf_ave[1,:,:] #* flag
# reshape back all the aligned version
for key in ['u_2','u_3','u_4','u_3f','u_4f','Z','Zf','conf','conff']:
self.vars_align[key] = tf.reshape(\
self.vars_align[key],
self.resolution[0]+(-1,)
)
#
self.valid_windowed_region_fuse()
# remove the bias
for key in ['Z']:
self.vars_fuse[key] -= Z_0[0]
self.vars_fuse[key] = -self.vars_fuse[key]
self.vars_align[key] -= Z_0[0]
self.vars_align[key] = -self.vars_align[key]
for key in ['Zf']:
self.vars_fuse[key] -= Z_0f[0]
self.vars_fuse[key] = -self.vars_fuse[key]
self.vars_align[key] -= Z_0f[0]
self.vars_align[key] = -self.vars_align[key]
# # temporal averaging
# conf_old = tf.Variable(self.vars_fuse['conf'], dtype=tf.float32)
# l = 0.91
# self.vars_fuse['conf'] = l*self.vars_fuse['conf']+(1-l)*conf_old
# conf_old = self.vars_fuse['conf']
#add values
#as number the inputs depends on num_py,
#we use string operations to do it
#add values
#as number the inputs depends on num_py,
#we use string operations to do it
self.input_data = tf.group(\
I.assign(self.I_in), a1.assign(self.a1_in), offset.assign(self.offset_in)
)
#do not add anything to the compute graph
#after this line
init_op = tf.global_variables_initializer()
self.session.run(init_op)
def align_maps_ext(self, vars_to_fuse = None):
# this function aligns different
# res into the same one
if vars_to_fuse == None:
vars_to_fuse = self.vars_to_fuse
shp = self.resolution[0]
for var in vars_to_fuse:
self.vars_align[var] = []
for i in range(len(self.cfg)):
# align depth map and confidence
self.vars_align[var].append(\
tf.image.resize_bilinear(\
tf.expand_dims(
self.vars[i][var],0
),\
shp,
align_corners = True
)\
)
# concatenate the depth maps and confidence
self.vars_align[var] = tf.squeeze(
tf.concat(self.vars_align[var], 3), [0]
)
return
def softmax_fusion(self):
ws = tf.nn.softmax(self.vars_align['conf']*1e10)
# fuse the results using softmax
for var in self.vars_to_fuse:
self.vars_fuse[var] = \
tf.reshape(
tf.reduce_sum(
self.vars_align[var]*ws,
[1]
), self.resolution[0]
)
conf_flat = self.vars_align['conff']
ws = tf.nn.softmax(conf_flat*1e10)
# fuse the results using softmax
for var in self.vars_to_fuse:
self.vars_fuse[var+'f'] = \
tf.reshape(
tf.reduce_sum(
self.vars_align[var+'f']*ws,
[1]
), self.resolution[0]
)
return
def w3_baseline_conf(self):
# this function computes the confidence and
# uncertainty according to stability,
# use the working range to cut the confidence
# and use weight for each layer
# the windowed flag indicates whether we compute windowed
w_bc = [] # the weight of baseline confidence for each layer
w_bc1 = []
w_bc2 = []
for i in range(len(self.cfg)):
# weights
w_bc.append(\
tf.constant(
self.cfg[i]['w_bc'],
dtype = tf.float32
)
)
w_bc1.append(\
tf.constant(
self.cfg[i]['w_bc1'],
dtype = tf.float32
)
)
w_bc2.append(\
tf.constant(
self.cfg[i]['w_bc2'],
dtype = tf.float32
)
)
w_bc = tf.concat(w_bc,0)
w_bc1 = tf.concat(w_bc1,0)
w_bc2 = tf.concat(w_bc2,0)
u_3 = self.vars_align['u_3']
u_32 = u_3**2
u_4 = self.vars_align['u_4']
u_42 = u_4**2
self.vars_align['conf'] = (u_42 + 1e-20)/\
tf.sqrt(\
tf.multiply(u_32, w_bc) + \
tf.multiply(u_42, w_bc1) + \
tf.multiply(u_3*u_4, w_bc2) + \
u_42**2 + 1e-10
)
self.vars_align['conff'] = self.vars_align['conf']
return
def valid_windowed_region_fuse(self):
# cut out the bad part
vars_to_cut = [\
'Z','conf','Zf','conff'\
]
rows_cut = int(\
((self.cfg[-1]['gauss'].shape[0]-1)/2+\
(self.cfg[-1]['ext_f'].shape[1]-1)/2)*\
self.resolution[0][0]/self.resolution[-1][0]
)
cols_cut = int(\
((self.cfg[-1]['gauss'].shape[1]-1)/2+\
(self.cfg[-1]['ext_f'].shape[2]-1)/2)*\
self.resolution[0][1]/self.resolution[-1][1]
)
rows = self.cfg[0]['szx_sensor']
cols = self.cfg[0]['szy_sensor']
for var in vars_to_cut:
self.vars_fuse[var] = \
self.vars_fuse[var][
cols_cut:cols-cols_cut,
rows_cut:rows-rows_cut
]
self.vars_align[var] = \
self.vars_align[var][
cols_cut:cols-cols_cut,
rows_cut:rows-rows_cut,
:
]
return
"""imports a frame into """
def process(self):
global results
# input the data
self.input_dict[self.I_in] = I_cache
self.input_dict[self.a1_in] = self.cfg[0]['a1']
self.input_dict[self.offset_in] = self.offset
self.session.run(self.input_data, self.input_dict)
# run it
self.image_to_show = ['Z','Zf','conf','u_2']
res_dict = {}
for k in self.image_to_show:
res_dict[k] = self.vars_fuse[k]
self.results = self.session.run(res_dict)
# if self.robust_mode == 'tracker':
# # keep the correct sequence
# self.keep_sequence()
self.swap_frames()
results = self.results
return
def keep_sequence(self):
# keep the correct sequence
if self.frames_track > self.old_num:
self.results['Z'], self.results['conf'], \
self.results['Zf'], self.results['conff'] \
= self.robust_depth(\
self.old_data['Z'],\
self.results['Z'],\
self.results['conf'],\
self.results['Zf'],\
self.results['conff'],
)
self.old_data['Z'][self.old_idx] = self.results['Z']
self.old_data['conf'][self.old_idx] = self.results['conf']
self.old_idx = np.mod(self.old_idx+1, self.old_num)
def swap_frames(self):
global I_cache
global ending_key
global I_idx
if ending_key == 's':
# for i in range(len(self.old_data['Z'])):
# self.old_data['Z'][i] = self.results['Zf']