-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcellCode.py
More file actions
executable file
·1129 lines (810 loc) · 26.6 KB
/
cellCode.py
File metadata and controls
executable file
·1129 lines (810 loc) · 26.6 KB
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
# coding: utf-8
# In[5]:
import pawData
reload(pawData)
import myutils
reload(myutils)
pawData.createDB()
# In[6]:
kk = np.zeros([3,5,2])
kk[:,:,:] = np.nan
print kk
np.any(np.isnan(kk),axis=(0,1))
# In[ ]:
import sys
sys.path.append('/home/mayank/work/pyutils')
sys.path.append('/home/mayank/work/tensorflow')
import pawMulti
reload(pawMulti)
import myutils
reload(myutils)
import pawconfig
reload(pawconfig)
import multiPawTools
reload(multiPawTools)
pawMulti.train()
# In[ ]:
sess = tf.InteractiveSession()
# In[ ]:
import scipy.io as sio
import os,sys
sys.path.append('/home/mayank/work/pyutils')
import myutils
import re
import pawconfig as conf
get_ipython().magic(u'matplotlib inline')
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy
import cv2
import math
import lmdb
import caffe
from random import randint
from multiPawTools import scalepatches
L = sio.loadmat(conf.labelfile)
pts = L['pts']
ts = L['ts']
expid = L['expidx']
# In[ ]:
frames = np.where(expid[0,:]==4)[0]
fnum = ts[0,frames]
cap = cv2.VideoCapture('/home/mayank/Dropbox/AdamVideos/multiPoint/M118_20140730/M118_20140730_v002/movie_comb.avi')
print(cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))
cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES,1)
stat,framein1 = cap.read()
cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES,2)
stat,framein2 = cap.read()
framein1 = framein1.astype('float')
framein2 = framein2.astype('float')
ddff = framein1-framein2
ddff = np.abs(ddff).astype('uint8')
print(stat)
if stat:
plt.imshow(ddff)
print(ddff.max())
cap.release()
# In[ ]:
import myutils
reload(myutils)
import cv2
cap = cv2.VideoCapture('/home/mayank/Dropbox/AdamVideos/multiPoint/M118_20140730/M118_20140730_v002/movie_comb.avi')
ff = myutils.readframe(cap,1998)
print(cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT ))
cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, 1998)
print(cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES))
stat,ff = cap.read()
print(cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES))
print(stat)
# In[ ]:
import moviepy.video.io.ffmpeg_reader as freader
reader = freader.FFMPEG_VideoReader('/home/mayank/Dropbox/AdamVideos/multiPoint/M118_20140730/M118_20140730_v002/movie_comb.avi')
f1 = reader.get_frame((-2.-0.1)/reader.fps)
f2 = reader.get_frame((1.-0.1)/reader.fps)
fe = reader.get_frame((1998.-0.1)/reader.fps)
type(f1)
# In[ ]:
import cv2
cap = cv2.VideoCapture('/home/mayank/Dropbox/AdamVideos/movie_comb.avi')
# In[ ]:
import pawconfig as conf
import scipy.io as sio
reload(conf)
L = sio.loadmat(conf.labelfile)
pts = L['pts']
ts = L['ts']
expid = L['expidx']
expid[0,3]
# In[ ]:
import lmdb
env = lmdb.open('cacheHead/val_lmdb', readonly=True)
txn = env.begin()
print(env.stat())
# In[ ]:
env.close()
# In[ ]:
import caffe
import numpy as np
import re
import matplotlib.pyplot as plt
import pawData
reload(pawData)
cursor =txn.cursor()
cursor.first()
# In[ ]:
import multiPawTools
reload(multiPawTools)
import pawconfig as conf
img,locs = multiPawTools.readLMDB(cursor,3,1)
# In[ ]:
from scipy import misc
from scipy import ndimage
reload(multiPawTools)
reload(conf)
plt.gray()
ndx = 2
img = img.transpose([0,2,3,1])
plt.imshow(img[ndx,:,:,0])
plt.show()
blurL = multiPawTools.createLabelImages(locs,conf.imsz,conf.rescale*conf.pool_scale,
conf.label_blur_rad,1)
x0 = multiPawTools.scaleImages(img,conf.rescale)
x1 = multiPawTools.scaleImages(x0,conf.scale)
x2 = multiPawTools.scaleImages(x1,conf.scale)
# labels = np.zeros([img.shape[2]/4,img.shape[3]/4])
# labels[int(locs[ndx][1])/4,int(locs[ndx][0])/4] = 1
# blurL = ndimage.gaussian_filter(labels,sigma = 3)
# blurL = blurL/blurL.max()
plt.imshow(blurL[ndx,:,:,0])
plt.show()
plt.imshow(x2[ndx,:,:,0])
plt.show()
print(blurL.max(),blurL.min())
# In[ ]:
print(blurL[ndx,5:12,35:42,0])
# In[ ]:
print(blurL.shape)
# In[ ]:
from scipy import misc
sz = img.shape
scale =2
simg = np.zeros((sz[0],sz[1],sz[2]/scale,sz[3]/scale))
for ndx in range(sz[0]):
for chn in range(sz[1]):
simg[ndx,chn,:,:] = misc.imresize(img[ndx,chn,:,:],1./scale)
plt.gray()
plt.imshow(simg[1,0,:,:])
plt.show()
plt.imshow(img[1,0,:,:])
plt.show()
# In[ ]:
env.close()
# In[ ]:
import pawMulti
reload(pawMulti)
import pawconfig as conf
reload(conf)
import tensorflow as tf
imsz = conf.imsz
x0 = tf.placeholder(tf.float32, [None, imsz[0],imsz[1],1])
x1 = tf.placeholder(tf.float32, [None, imsz[0]/2,imsz[1]/2,1])
x2 = tf.placeholder(tf.float32, [None, imsz[0]/4,imsz[1]/4,1])
dropout = tf.placeholder(tf.float32)
labelimg = tf.placeholder(tf.float32, [None, imsz[0]/4,imsz[1]/4,1])
weights = pawMulti.initNetConvWeights()
pred = pawMulti.paw_net_multi_conv(x0,x1,x2,weights,dropout)
# In[ ]:
import numpy as np
imsz = conf.imsz
jj = np.ones([3,imsz[0],imsz[1],1])
jj1 = np.ones([3,imsz[0]/2,imsz[1]/2,1])
jj2 = np.ones([3,imsz[0]/4,imsz[1]/4,1])
sess.run(tf.initialize_all_variables())
out = sess.run(pred,feed_dict = {x0:jj,x1:jj1,x2:jj2,labelimg:jj2,dropout:1.})
print(out.shape)
print(jj2.shape)
# In[ ]:
sess = tf.InteractiveSession()
# In[ ]:
import tensorflow as tf
import numpy as np
x0 = tf.placeholder(tf.float32,[3,4])
jj = np.arange(12).reshape([2,3,2])
indices0 = tf.range(0,2*tf.shape(x0)[1],2)
indices1 = tf.range(1,2*tf.shape(x0)[1],2)
indices2 = tf.range(0,2*tf.shape(x0)[2],2)
indices3 = tf.range(1,2*tf.shape(x0)[2],2)
x1 = tf.transpose(tf.dynamic_stitch([indices0,indices1],[x0,x0]),[1,0])
x2 = tf.transpose(tf.dynamic_stitch([indices2,indices3],[x1,x1]),[1,0])
sess.run(tf.initialize_all_variables())
out = sess.run([x1,x2],feed_dict={x0:jj})
print(jj)
print(out[1])
# In[ ]:
sess.close()
# In[ ]:
import tensorflow as tf
import os,sys
sys.path.append('/home/mayank/work/caffe/python')
import caffe
import lmdb
import caffe.proto.caffe_pb2
import pawconfig as conf
from caffe.io import datum_to_array
get_ipython().magic(u'matplotlib inline')
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy
import multiPawTools
import math
import pawMulti
learning_rate = conf.learning_rate
training_iters = conf.training_iters
batch_size = conf.batch_size
display_step = conf.display_step
# Network Parameters
n_input = conf.psz
n_classes = conf.n_classes #
dropout = conf.dropout # Dropout, probability to keep units
imsz = conf.imsz
# tf Graph input
keep_prob = tf.placeholder(tf.float32) # dropout(keep probability)
x0 = tf.placeholder(tf.float32, [None,
imsz[0]/conf.rescale,
imsz[1]/conf.rescale,1])
x1 = tf.placeholder(tf.float32, [None,
imsz[0]/conf.scale/conf.rescale,
imsz[1]/conf.scale/conf.rescale,1])
x2 = tf.placeholder(tf.float32, [None,
imsz[0]/conf.scale/conf.scale/conf.rescale,
imsz[1]/conf.scale/conf.scale/conf.rescale,1])
lsz0 = int(math.ceil(float(imsz[0])/conf.pool_scale/conf.rescale))
lsz1 = int(math.ceil(float(imsz[1])/conf.pool_scale/conf.rescale))
y = tf.placeholder(tf.float32, [None, lsz0,lsz1,n_classes])
lmdbfilename =os.path.join(conf.cachedir,conf.trainfilename)
vallmdbfilename =os.path.join(conf.cachedir,conf.valfilename)
env = lmdb.open(lmdbfilename, map_size=conf.map_size)
valenv = lmdb.open(vallmdbfilename, map_size=conf.map_size)
txn = env.begin(write=True)
valtxn = valenv.begin(write=True)
train_cursor = txn.cursor()
val_cursor = valtxn.cursor()
weights = pawMulti.initNetConvWeights()
# Construct model
pred =pawMulti.paw_net_multi_conv(x0,x1,x2, weights, keep_prob)
# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.l2_loss(pred- y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
init = tf.initialize_all_variables()
saver = tf.train.Saver()
sess = tf.InteractiveSession()
sess.run(init)
saver.restore(sess, 'cache/pawMulti_r2_s3_20000.ckpt')
val_xs, locs = multiPawTools.readLMDB(val_cursor,batch_size*4,n_classes)
x0_in = multiPawTools.scaleImages(val_xs.transpose([0,2,3,1]),conf.rescale)
x1_in = multiPawTools.scaleImages(x0_in,conf.scale)
x2_in = multiPawTools.scaleImages(x1_in,conf.scale)
labelims = multiPawTools.createLabelImages(locs,
conf.imsz,conf.pool_scale*conf.rescale,
conf.label_blur_rad,1)
out = sess.run([pred,cost], feed_dict={x0:x0_in,
x1:x1_in,
x2:x2_in,
y: labelims, keep_prob: 1.})
# In[ ]:
import matplotlib.pyplot as plt
from IPython import display
import time
plt.ion()
fig,axs = plt.subplots(1,3)
plt.gray()
for ndx in range(256):
plt.sca(axs[0])
plt.imshow(x0_in[ndx,:,:,0])
display.clear_output(wait=True)
# display.display(plt.gcf())
plt.sca(axs[1])
plt.imshow(out[0][ndx,:,:,0])
display.clear_output(wait=True)
# display.display(plt.gcf())
plt.sca(axs[2])
plt.imshow(labelims[ndx,:,:,0])
display.clear_output(True)
display.display(fig)
time.sleep(1)
# In[ ]:
import cv2
import matplotlib.animation as manimation
sys.path.append('/home/mayank/work/pyutils')
import myutils
import matplotlib
import tempfile
curdir = '/home/mayank/Dropbox/AdamVideos/multiPoint/M122_20140828/M122_20140828_v002'
tdir = tempfile.mkdtemp()
# plt.rcParams['animation.ffmpeg_path'] = '/usr/bin/ffmpeg'
# FFMpegWriter = manimation.writers['mencoder_file']
# writer = FFMpegWriter(fps=15,bitrate=2000)
fig = plt.figure()
cap = cv2.VideoCapture(os.path.join(curdir,'movie_comb.avi'))
nframes = int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))
plt.gray()
# with writer.saving(fig,"test_results.mp4",4):
count = 0
vidfilename = 'paw_detect.avi'
for fnum in range(nframes):
plt.clf()
framein = myutils.readframe(cap,fnum)
framein = framein[np.newaxis,:,0:(framein.shape[1]/2),0:1]
x0_in = multiPawTools.scaleImages(framein,conf.rescale)
x1_in = multiPawTools.scaleImages(x0_in,conf.scale)
x2_in = multiPawTools.scaleImages(x1_in,conf.scale)
labelim = np.zeros([1,33,44,1])
out = sess.run(pred, feed_dict={x0:x0_in,
x1:x1_in,
x2:x2_in,
y:labelim,
keep_prob: 1.})
plt.imshow(x0_in[0,:,:,0])
maxndx = np.argmax(out[0,:,:,0])
loc = np.unravel_index(maxndx,out.shape[1:3])
plt.scatter(loc[1]*4,loc[0]*4,hold=True)
fname = "test_{:06d}.png".format(count)
plt.savefig(os.path.join(tdir,fname))
count+=1
# plt.imshow(out[0,:,:,0])
# fname = "test_heat_{:d}.png".format(fnum)
# plt.savefig(fname)
# writer.grab_frame()
ffmpeg_cmd = "ffmpeg -r 30 " + "-f image2 -i '/path/to/your/picName%d.png' -qscale 0 '/path/to/your/new/video.avi'
tfilestr = os.path.join(tdir,'test_*.png')
mencoder_cmd = "mencoder mf://" + tfilestr + " -frames " + "{:d}".format(count) + " -mf type=png:fps=15 -o " + vidfilename + " -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=2000000"
print(mencoder_cmd)
os.system(mencoder_cmd)
cap.release()
# In[ ]:
import pawData
a,b,c = pawData.loadValdata()
# In[ ]:
import pawData
import pawMulti
import scipy.io as sio
import pawconfig as conf
reload(pawMulti)
reload(conf)
import os
import numpy as np
import tensorflow as tf
import tempfile
import matplotlib.pyplot as plt
import cv2
import sys,copy
sys.path.append('/home/mayank/work/pyutils')
import myutils
isval,localdirs,seldirs = pawData.loadValdata()
model_file = 'cache/pawMulti_r2_s3_20000.ckpt'
movcount = 0
maxcount = 5
L = sio.loadmat(conf.labelfile)
pts = L['pts']
ts = L['ts']
expid = L['expidx']
pred,saver,pholders = pawMulti.initPredSession()
tdir = tempfile.mkdtemp()
plt.gray()
# with writer.saving(fig,"test_results.mp4",4):
fig = plt.figure()
with tf.Session() as sess:
saver.restore(sess, model_file)
for ndx,dirname in enumerate(localdirs):
if movcount> maxcount:
break
if not seldirs[ndx]:
continue
expname = os.path.basename(dirname)
frames = np.where(expid[0,:] == (ndx + 1))[0]
curdir = localdirs[ndx]
outmovie = expname + ".avi"
cap = cv2.VideoCapture(os.path.join(curdir,'movie_comb.avi'))
nframes = int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))
count = 0
for fnum in range(nframes):
plt.clf()
plt.axis('off')
framein = myutils.readframe(cap,fnum)
framein = framein[:,0:(framein.shape[1]/2),0:1 out = pawMulti.predict(copy.copy(framein),sess,pred,pholders)
plt.imshow(framein[:,:,0])
maxndx = np.argmax(out[0,:,:,0])
loc = np.unravel_index(maxndx,out.shape[1:3])
scalefactor = conf.rescale*conf.pool_scale
plt.scatter(loc[1]*scalefactor,loc[0]*scalefactor,hold=True)
fname = "test_{:06d}.png".format(count)
plt.savefig(os.path.join(tdir,fname))
count+=1
# ffmpeg_cmd = "ffmpeg -r 30 " + \
# "-f image2 -i '/path/to/your/picName%d.png' -qscale 0 '/path/to/your/new/video.avi'
tfilestr = os.path.join(tdir,'test_*.png')
mencoder_cmd = "mencoder mf://" + tfilestr + \
" -frames " + "{:d}".format(count) + " -mf type=png:fps=15 -o " + \
outmovie + " -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=2000000"
# print(mencoder_cmd)
os.system(mencoder_cmd)
cap.release()
movcount+=1
# In[ ]:
import tensorflow as tf
sess = tf.InteractiveSession()
kk = tf.constant([3,-2,0.1,-0.05,5])
ss = tf.sign(kk)
mm = tf.mul(ss,tf.maximum(tf.abs(kk)-0.2,0))
aa = mm.eval()
print(aa)
# In[ ]:
import lmdb
lmdbfilename= 'cacheHeadSide/train_lmdb'
env = lmdb.open(lmdbfilename, readonly = True)
txn = env.begin()
print(txn.stat()['entries'])
# In[ ]:
import PoseTools
import multiResData
cursor = txn.cursor()
ii,ll = PoseTools.readLMDB(cursor,1,[512, 512],multiResData)
print ii.shape
print ll
plt.imshow(ii[0,0,:,:])
# In[ ]:
import pickle
with open('cacheHead/headMRFtraindata','rb') as f:
gg = pickle.load(f)
# In[ ]:
print gg[0].keys()
plt.clf()
x = gg[0]['step_no'][5:]
plt.plot(x,gg[0]['val_base_dist'][5:])
plt.plot(x,gg[0]['val_dist'][5:], hold=True)
plt.legend(('base','mrf'))
# In[ ]:
from janLegConfig import conf as conf
# from stephenHeadConfig import sideconf as conf
import PoseTools
jj = PoseTools.initMRFweights(conf)
jj.shape
for ndx in range(conf.n_classes):
fig = plt.figure()
for ii in range(conf.n_classes):
ax1 = fig.add_subplot(2,2,ii+1)
ax1.imshow(jj[:,:,ndx,ii],interpolation='nearest',vmax=1.,vmin=0.)
plt.show()
# In[ ]:
np.set_printoptions(precision=2)
# print jj[35:45,35:45,0,1]
print np.array_str(jj[35:45,35:45,2,3],precision=2,suppress_small = True)
# In[ ]:
from stephenHeadConfig import conf as conf
import multiResData
a,b,c = multiResData.loadValdata(conf)
print max(int(len(a)/conf.holdoutratio),1)
print len(a)
print a
print a.index(88)
# In[ ]:
from stephenHeadConfig import conf as conf
import multiResData
isval,a,b = multiResData.loadValdata(conf)
n_ho = min(max(int(len(isval)*conf.holdoutratio),1),len(isval)-1)
print n_ho
print isval.index(73)
print len(isval)
# In[ ]:
from stephenHeadConfig import conf as conf
import multiResData
reload(multiResData)
_,x = multiResData.getMovieLists(conf)
x
# In[ ]:
from stephenHeadConfig import conf as conf
import multiResData
import cv2
print cl
_,valmovies = multiResData.getMovieLists(conf)
ndx = -3
cap = cv2.VideoCapture(valmovies[ndx])
height = int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT))
width = int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH))
orig_crop_loc = conf.cropLoc[(height,width)]
crop_loc = [x/4 for x in orig_crop_loc]
print orig_crop_loc
# In[ ]:
from matplotlib import cm
cmap = cm.get_cmap('jet')
rgba = cmap(np.linspace(0,1,4))
print rgba
ii = np.zeros([4,4,3])
for ndx in range(4):
ii[:,ndx,:] =cm.hsv(0+1./4.*ndx)[0:3]
plt.imshow(ii)
# In[ ]:
import PoseTrain
reload(PoseTrain)
from stephenHeadConfig import conf as conf
import tensorflow as tf
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '2'
pobj = PoseTrain.PoseTrain(conf)
pobj.mrfTrain(restore=False)
# In[ ]:
import multiResData
from stephenHeadConfig import conf as conf
_,valmovies = multiResData.getMovieLists(conf)
# In[ ]:
print valmovies[0][17:]
# In[ ]:
# create a list of movies for stephen -- May 23 2016
import os
with open("/groups/branson/bransonlab/mayank/PoseEstimationData/Stephen/folders2track.txt", "r") as text_file:
movies = text_file.readlines()
movies = [x.rstrip() for x in movies]
import glob
sdir = movies[0::2]
fdir = movies[1::2]
fmovies = []
smovies = []
for ndx,ff in enumerate(sdir):
kk = glob.glob(ff+'/*_c.avi')
if len(kk) is not 1:
print ff
continue
smovies.append(kk[0])
kk = glob.glob(fdir[ndx]+'/*_c.avi')
fmovies += kk
print smovies[0:3]
print fmovies[0:3]
print len(smovies)
print len(fmovies)
for ff in smovies+fmovies:
if not os.path.isfile(ff):
print ff
# In[ ]:
import localSetup
import PoseTools
reload(PoseTools)
import multiResData
reload(multiResData)
import os
import re
import tensorflow as tf
from scipy import io
# from stephenHeadConfig import sideconf as conf
# conf.useMRF = False
# extrastr = '_side'
# outtype = 1
os.environ['CUDA_VISIBLE_DEVICES'] = '2'
from stephenHeadConfig import conf as conf
conf.useMRF = True
outtype = 2
extrastr = ''
redo = False
# conf.batch_size = 1
self = PoseTools.create_network(conf, outtype)
sess = tf.InteractiveSession()
PoseTools.init_network(self, sess, outtype)
from scipy import io
import cv2
# _,valmovies = multiResData.getMovieLists(conf)
# for ndx in range(len(valmovies)):
# valmovies[ndx] = '/groups/branson/bransonlab/mayank/' + valmovies[ndx][17:]
# for ndx in [0,3,-3,-1]:
# valmovies = ['/groups/branson/bransonlab/projects/flyHeadTracking/ExamplefliesWithNoTrainingData/fly138/fly138_trial1/C002H001S0001/C002H001S0001_c.avi',
# '/groups/branson/bransonlab/projects/flyHeadTracking/ExamplefliesWithNoTrainingData/fly138/fly138_trial2/C002H001S0001/C002H001S0001_c.avi',
# '/groups/branson/bransonlab/projects/flyHeadTracking/ExamplefliesWithNoTrainingData/fly138/fly138_trial3/C002H001S0001/C002H001S0001_c.avi',
# '/groups/branson/bransonlab/projects/flyHeadTracking/ExamplefliesWithNoTrainingData/fly138/fly138_trial4/C002H001S0001/C002H001S0001_c.avi',
# '/groups/branson/bransonlab/projects/flyHeadTracking/ExamplefliesWithNoTrainingData/fly163/fly163_trial1/C002H001S0001/C002H001S0001_c.avi',
# '/groups/branson/bransonlab/projects/flyHeadTracking/ExamplefliesWithNoTrainingData/fly163/fly163_trial2/C002H001S0001/C002H001S0001_c.avi',
# '/groups/branson/bransonlab/projects/flyHeadTracking/ExamplefliesWithNoTrainingData/fly163/fly163_trial3/C002H001S0001/C002H001S0001_c.avi',
# '/groups/branson/bransonlab/projects/flyHeadTracking/ExamplefliesWithNoTrainingData/fly163/fly163_trial4/C002H001S0001/C002H001S0001_c.avi',
# ]
# for ndx in range(len(valmovies)):
valmovies = fmovies
for ndx in range(len(valmovies)):
mname,_ = os.path.splitext(os.path.basename(valmovies[ndx]))
oname = re.sub('!','__',conf.getexpname(valmovies[ndx]))
# pname = '/groups/branson/home/kabram/bransonlab/PoseTF/results/headResults/movies/' + oname + extrastr
pname = '/nobackup/branson/mayank/stephenOut/' + oname + extrastr
if os.path.isfile(pname + '.mat') and not redo:
continue
predList = PoseTools.classify_movie(conf, valmovies[ndx], outtype, self, sess)
if ndx<5:
PoseTools.create_pred_movie(conf, predList, valmovies[ndx], pname + '.avi', outtype)
cap = cv2.VideoCapture(valmovies[ndx])
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
orig_crop_loc = conf.cropLoc[(height,width)]
crop_loc = [x/4 for x in orig_crop_loc]
end_pad = [height/4-crop_loc[0]-conf.imsz[0]/4,width/4-crop_loc[1]-conf.imsz[1]/4]
pp = [(0,0),(crop_loc[0],end_pad[0]),(crop_loc[1],end_pad[1]),(0,0),(0,0)]
predScores = np.pad(predList[1],pp,mode='constant',constant_values=-1.)
predLocs = predList[0]
predLocs[:,:,:,0] += orig_crop_loc[1]
predLocs[:,:,:,1] += orig_crop_loc[0]
io.savemat(pname + '.mat',{'locs':predLocs,'scores':predScores[...,0],'expname':valmovies[ndx]})
print "Done prediction for %s" %oname
print pp
print predList[1].shape
# In[ ]:
# creating movie for lab talk 20160611
import localSetup
import PoseTools
reload(PoseTools)
import multiResData
reload(multiResData)
import os
import re
import tensorflow as tf
from scipy import io
# from stephenHeadConfig import sideconf as conf
# conf.useMRF = False
# extrastr = '_side'
# outtype = 1
os.environ['CUDA_VISIBLE_DEVICES'] = '2'
from stephenHeadConfig import conf as conf
conf.useMRF = False
outtype = 1
extrastr = ''
redo = False
# conf.batch_size = 1
self = PoseTools.create_network(conf, outtype)
sess = tf.InteractiveSession()
PoseTools.init_network(self, sess, outtype)
from scipy import io
import cv2
_,valmovies = multiResData.get_movie_lists(conf)
for ndx in range(len(valmovies)):
valmovies[ndx] = '/groups/branson/bransonlab/mayank/' + valmovies[ndx][17:]
for ndx in [0,3,-3,-1]:
mname,_ = os.path.splitext(os.path.basename(valmovies[ndx]))
oname = re.sub('!','__',conf.getexpname(valmovies[ndx]))
# pname = '/groups/branson/home/kabram/bransonlab/PoseTF/results/headResults/movies/' + oname + extrastr
pname = '/nobackup/branson/mayank/stephenOut/forDrosoneuroBase_'+ oname + extrastr
if os.path.isfile(pname + '.mat') and not redo:
continue
predList = PoseTools.classify_movie(conf, valmovies[ndx], outtype, self, sess)
if ndx<5:
PoseTools.create_pred_movie(conf, predList, valmovies[ndx], pname + '.avi', outtype)
# cap = cv2.VideoCapture(valmovies[ndx])
# height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
# orig_crop_loc = conf.cropLoc[(height,width)]
# crop_loc = [x/4 for x in orig_crop_loc]
# end_pad = [height/4-crop_loc[0]-conf.imsz[0]/4,width/4-crop_loc[1]-conf.imsz[1]/4]
# pp = [(0,0),(crop_loc[0],end_pad[0]),(crop_loc[1],end_pad[1]),(0,0),(0,0)]
# predScores = np.pad(predList[1],pp,mode='constant',constant_values=-1.)
# predLocs = predList[0]
# predLocs[:,:,:,0] += orig_crop_loc[1]
# predLocs[:,:,:,1] += orig_crop_loc[0]
# io.savemat(pname + '.mat',{'locs':predLocs,'scores':predScores[...,0],'expname':valmovies[ndx]})
print "Done prediction for %s" %oname
# In[ ]:
# Compute Errors for validation.
import os
import localSetup
import PoseTools
import PoseTrain
import caffe
from stephenHeadConfig import conf as conf
import tensorflow as tf
from matplotlib import cm
os.environ['CUDA_VISIBLE_DEVICES'] = '2'
conf.useMRF = True
conf.useAC = False
conf.batch_size = 1;
outtype = 3
self = PoseTools.create_network(conf, outtype)
self.open_dbs()
sess = tf.InteractiveSession()
PoseTools.init_network(self, sess, outtype)
nval = int(self.valenv.stat()['entries'])
predErr = np.zeros([3,conf.n_classes,2,nval])
with self.valenv.begin() as valtxn:
self.val_cursor = valtxn.cursor()
self.val_cursor.first()
for ndx in range(nval):
self.feed_dict[self.ph['keep_prob']] = 1.
self.feed_dict[self.ph['learning_rate']] = 1.
self.updateFeedDict(self.DBType.Val)
preds = sess.run([self.basePred,self.mrfPred,self.finePred],feed_dict=self.feed_dict)
predErr[0,:,:,ndx] = PoseTools.get_base_error(self.locs, preds[0], conf)[0, ...]
mrfErr,fineErr = PoseTools.get_fine_error(self.locs, preds[1], preds[2], conf)
predErr[1,:,:,ndx] = mrfErr[0,...]
predErr[2,:,:,ndx] = fineErr[0,...]
gg = np.sqrt( (np.square(predErr[:,:,0,:])+np.square(predErr[:,:,0,:])))
hh = np.mean(gg,2)
with self.valenv.begin() as valtxn:
self.val_cursor = valtxn.cursor()
self.val_cursor.first()
for ndx in range(12):
self.updateFeedDict(self.DBType.Val)
cc=cm.hsv(np.linspace(0,1-1./conf.n_classes,conf.n_classes))
xx = self.feed_dict[self.ph['x0']]
ll = self.locs[0,:,:]
fig = plt.figure(figsize = (6,20))
for ii in range(3):
llb = np.tile(ll[...,np.newaxis],[1,1,predErr.shape[-1]]) + predErr[ii,...]
ax1 = fig.add_subplot(3,1,ii+1)
ax1.imshow(xx[0,...,0], cmap=cm.gray)
for ndx in range(conf.n_classes):
ax1.scatter(llb[ndx,0,:].flatten(),llb[ndx,1,:].flatten(),c=cc[ndx:ndx+1,:],edgecolors='face',s=5,alpha=1)
ax1.axis('off')
ax1.set_title('%.2f'%hh.mean(1)[ii])
fig.savefig('/groups/branson/home/kabram/temp/headValResults.png')
# In[ ]:
import multiResData
from stephenHeadConfig import conf as conf
_,valmovies = multiResData.get_movie_lists(conf)
f = open('/home/mayank/Dropbox/temp/valfilelist.txt','w')
for ndx in range(40,50):
f.write('{:}\n'.format(valmovies[ndx]))
f.close()
# In[ ]:
import h5py
L = h5py.File('/home/mayank/temp/romainTest.lbl','r')
# In[ ]:
print L.keys()