-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgp_swimming.py
1974 lines (1582 loc) · 82.3 KB
/
gp_swimming.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
###################################################################################
#Swimming analysis in agar
#Github: https://github.com/jonascremer/swimming_analysis
###################################################################################
#
#This Python code analyzes swimming behavior of motile bacteria. The code was used
#to analyze the movement characteristics of cells in liquid conditions. We used it
# for our manuscript:
#J.Cremer, T.Honda, Y.Tang, J.Wong-Ng, M.Vergassola, T.Hwa.
#Chemotaxis as a navigation strategy to thrive in nutrient-replete environments
#
#August 2019, Jonas Cremer together with the other coauthors.
#
#Additional information provided in "README.md"
#import needed packages
import trackpy
import cv2
import numpy as np
import json
import subprocess
from scipy import ndimage
import os, sys
import scipy.io
import pandas as pd
import scipy
import csv
import matplotlib
import matplotlib.pyplot as plt
import colormaps
cmaps=colormaps.cmaps
#####
#: Folders where raw movies are located
#####
maindirc=os.getcwd() #output of file
datafolderrawvideo='/Volumes/xydrive'
datafolderrawvideo2='/Volumes/xydrive2'
#######
#the following define subfolders - they are generated if they don't exist
#######
data_detection=os.path.join(maindirc,"data_detection")
data_trajectories=os.path.join(datafolderrawvideo2,"data_trajectories")
data_analysisoutput=os.path.join(maindirc,"data_swimminganalysis")
folder_detectiontest=os.path.join(maindirc,"detection_test")
plot_controloutput=os.path.join(data_analysisoutput,"controloutput")
data_movieoutput=os.path.join(plot_controloutput,"movie_output")
trjstat_output=os.path.join( plot_controloutput,"trjstat_output")
#make sure folders are generated if they don't exist...
try:
if not os.path.exists(data_detection):
os.makedirs(data_detection)
else:
pass
if not os.path.exists(data_trajectories):
os.makedirs(data_trajectories)
else:
pass
if not os.path.exists(data_analysisoutput):
os.makedirs(data_analysisoutput)
else:
pass
if not os.path.exists(plot_controloutput):
os.makedirs(plot_controloutput)
else:
pass
if not os.path.exists(data_movieoutput):
os.makedirs(data_movieoutput)
else:
pass
if not os.path.exists(trjstat_output):
os.makedirs(trjstat_output)
else:
pass
except:
print "CHECK PATH HARDDRIVE"
def tresholdanalysis(substracted,mintreshold=0):
#go through different tresholds....take treshold with less than 1000 cells?
tresholdlist=range(mintreshold,255)
particlenum_treshold=np.zeros([255,2])
particlenum_treshold[:]=np.nan
tccount=-1
determineconstanttreshold=True
for treshold in tresholdlist:
tccount=tccount+1
#print "treshold test"
#print treshold
#image_to_be_labeled = ((difference_image > threshold) * 255).astype('uint8') # not sure if it is necessary
[haeh,image_to_be_labeled]=cv2.threshold(substracted,treshold,255,cv2.THRESH_BINARY)
#print np.nanmin(image_to_be_labeled)
#print np.nanmax(image_to_be_labeled)
labelarray, particle_count = scipy.ndimage.measurements.label(image_to_be_labeled)
#print particle_count
particlenum_treshold[tccount,0]=treshold
particlenum_treshold[tccount,1]=particle_count
if particle_count==1:
break
tresholdconstant=treshold
if tccount>1 and determineconstanttreshold:
if particlenum_treshold[tccount,1]<500.:
#print particlenum_treshold[tccount,1]
#print particlenum_treshold[tccount-1,1]
tresholdconstant=treshold
determineconstanttreshold=False
break
return [particlenum_treshold,tresholdconstant]
def remove_doubles(particlelist,particlelist_weight,distancemegere=5):
#go through particle list and merge close particles....
particlelist_new=[[particlelist[0][0],particlelist[0][1],particlelist_weight[0]]]
for ilc in range(1,len(particlelist)):
xc=particlelist[ilc][0]
yc=particlelist[ilc][1]
curweight=particlelist_weight[ilc]
nobreak=True
indxsame=[] #detected same particles...
indxweight=[]
for ilc2 in range(0,len(particlelist_new)):
xc2=particlelist_new[ilc2][0]
yc2=particlelist_new[ilc2][1]
dist=np.sqrt((xc2-xc)*(xc2-xc)+(yc2-yc)*(yc2-yc))
if dist<distancemegere:
nobreak=False
indxsame.append(ilc2)
indxweight.append(particlelist_new[ilc2][2])
if nobreak:
particlelist_new.append([xc,yc,curweight])
else:
#merge all the indexes to one...
indxheightest=indxweight.index(max(indxweight))
#remove all lower weight entries
for ilw in range(len(indxsame)-1,-1,-1):
if ilw==indxheightest:
if max(indxweight)>=curweight:
pass
else:
del particlelist_new[indxsame[ilw]]
particlelist_new.append([xc,yc,curweight])
else:
del particlelist_new[indxsame[ilw]]
#del indxweight[indxsame[ilw]]
#transform into array....
particlelist=np.array(particlelist_new) #shape: num particles, 2(xy position)
particlelist_weight=particlelist[:,2]
return [particlelist,particlelist_weight]
def select_particles(particlelist,particlelist_weight,percentage=0.05,num_m=0,minvalue=0):
if num_m==0:
num_m=5
num10=int(0.2*particlelist_weight.shape[0])
if num10>num_m: #this is to make sure that analysis is not messed up in case many non-cellular particles are detected
num10=num_m
ind_highest=particlelist_weight.argsort()[-num10]
avweight=particlelist_weight[ind_highest]#
if minvalue>0 and avweight<minvalue:
avweight=minvalue
weightselection=avweight*percentage
ind_selected=particlelist_weight>weightselection
particlelist_selected=particlelist[ind_selected,:]
return [particlelist_selected,weightselection]
#go through differnt detected cell runs and detect trajectories
def analysis(strcriteria1="",strcriteria2="",statisticalanalysis=False,framemax=3000,minduration=3,minlength_analysis=50,onlyselectiondisplay=False,repeat=True,excplude1=""):
filenmaelist=[]
listdir=os.listdir(data_detection)
for il in range(0,len(listdir)):
curn=listdir[il][:-4]
if listdir[il][-4:]==".npz":
#print curn
skip=False
if strcriteria1=="":
pass
else:
if strcriteria1 in curn:
pass
else:
skip=True
if strcriteria2=="":
pass
else:
if strcriteria2 in curn:
pass
else:
skip=True
if excplude1=="":
pass
else:
if excplude1 in curn:
skip=True
if "_background" in curn:
skip=True
if "_adaptive" in curn:
skip=True
if "_short" in curn:
skip=True
if skip==False:
filenmaelist.append(curn)
for ifile in filenmaelist:
#print ifile
dotra=False
if 3>2:
if 3>2:#==False:
ifilec=os.path.basename(ifile)
if ifilec[-4:]==".avi":
ifilec=ifilec[:-4]
filenameoutc=os.path.join(data_trajectories,ifilec+".pad")
if os.path.exists(filenameoutc)==False and onlyselectiondisplay==False:
dotra=True
elif not os.path.exists(filenameoutc):
print "Trajectory file does not exist: "+ifilec
else:
print "Trajectory file does exist: "+ifilec
if repeat==True and onlyselectiondisplay==False:
dotra=True
if dotra==True:
print "Generating trajectory: "+ifile
generate_trajectories(ifile,framemaxin=framemax,search_range=20, memory=4)
if statisticalanalysis:
analyze_trajectories(ifile,minduration=3)
#trajectory_statistics(ifile,framemaxin=framemax,minlength_analysis=minlength_analysis)
def get_folderentries(folder, strcriteria1="",strcriteria2="",excplude1="",ending=".pad"):
filenmaelist=[]
listdir=os.listdir(folder)
for il in range(0,len(listdir)):
curn=listdir[il][:-4]
if listdir[il][-4:]==ending:
#print curn
skip=False
if strcriteria1=="":
pass
else:
if strcriteria1 in curn:
pass
else:
skip=True
if strcriteria2=="":
pass
else:
if strcriteria2 in curn:
pass
else:
skip=True
if excplude1=="":
pass
else:
if excplude1 in curn:
skip=True
if "_background" in curn:
skip=True
if "_adaptive" in curn:
skip=True
if "_short" in curn:
skip=True
if skip==False:
filenmaelist.append(curn)
return filenmaelist
def detect_particles(imagein,imagein_timeav,blur_parameter=20,plot_controloutput=True,plot_outputname="",plot_annotatetext="",selectionfraction=0.05,selectionfraction2="",min_value_selectionbackground=0,fluorescencedata=False):
if selectionfraction2=="":
selectionfraction2=selectionfraction
gray = cv2.cvtColor(imagein, cv2.COLOR_BGR2GRAY)
gray_numpy = np.asarray(gray, dtype=float)
blurred_grayscale_numpy = scipy.ndimage.filters.gaussian_filter(gray_numpy, blur_parameter)
if fluorescencedata==False:
rescaled = 255-gray_numpy#np.abs(original_grayscale - np.nanmin(original_grayscale))#(multiplier * blurred_grayscale));
rescaled_blurred = 255-blurred_grayscale_numpy
else:
rescaled = gray_numpy#np.abs(original_grayscale - np.nanmin(original_grayscale))#(multiplier * blurred_grayscale));
rescaled_blurred = blurred_grayscale_numpy
#peaks removed
#go through different sub areas and determin max values
if fluorescencedata:
arlist=np.hsplit(gray_numpy,32) #go through 80 subareas
else:
arlist=np.hsplit(gray_numpy,80)
maxlist=[]
for il in range(0,len(arlist)):
maxlist.append(np.nanmax(arlist[il]))
maxlist=np.array(maxlist)
maxlist[::-1].sort()
cutoffmax=maxlist[8] #take 8th heights array as max cufoff
cutoffind = gray_numpy > cutoffmax
gray_numpy_cutoff=np.copy(gray_numpy)
if fluorescencedata==False: #do not use rescaling for fluorescence data
gray_numpy_cutoff[cutoffind] = cutoffmax
substracted=cv2.subtract(rescaled,rescaled_blurred)
scalefactor=255./np.nanmax(substracted)
scalefactor=255./65.
substracted=substracted*scalefactor
[particlenum_treshold,tresholdconstant]=tresholdanalysis(substracted,mintreshold=10)
#detect particles with determined treshold value
[haeh,tresholdimage]=cv2.threshold(substracted,tresholdconstant,255,cv2.THRESH_BINARY)
labelarray, particle_count = scipy.ndimage.measurements.label(tresholdimage)
particlelist=ndimage.measurements.center_of_mass(rescaled,labels=labelarray,index=range(1,particle_count+1))
particlelist_weight=ndimage.measurements.sum(rescaled,labels=labelarray,index=range(1,particle_count+1))
particlelist_size=ndimage.measurements.sum(tresholdimage,labels=labelarray,index=range(1,particle_count+1))/255.
[particlelist,particlelist_weight]=remove_doubles(particlelist,particlelist_weight)
substracted2=cv2.subtract(rescaled,imagein_timeav)
scalefactor2=255./np.nanmax(substracted2)
scalefactor2=255./22.
substracted2=substracted2*scalefactor2
[particlenum_treshold2,tresholdconstant2]=tresholdanalysis(substracted2,mintreshold=40)
[haeh,tresholdimage2]=cv2.threshold(substracted2,tresholdconstant2,255,cv2.THRESH_BINARY)
labelarray2, particle_count2 = scipy.ndimage.measurements.label(tresholdimage2)
particlelist2=ndimage.measurements.center_of_mass(substracted2,labels=labelarray2,index=range(1,particle_count2+1))
particlelist_weight2=ndimage.measurements.sum(substracted2,labels=labelarray2,index=range(1,particle_count2+1))
[particlelist2,particlelist_weight2]=remove_doubles(particlelist2,particlelist_weight2)
[particlelist_selected,weightselection]=select_particles(particlelist,particlelist_weight,selectionfraction) #percentage to sort out
[particlelist_selected2,weightselection2]=select_particles(particlelist2,particlelist_weight2,selectionfraction2,num_m=1,minvalue=min_value_selectionbackground) #percentage to sort out
strout1= "# "+str(particle_count)+"\n #_sel"+str(round(particlelist_selected.shape[0]))+"\n Wmax"+str(round(np.nanmax(particlelist_weight)))+"\n Wu: "+str(round(weightselection/selectionfraction))
strout2= "# "+str(particle_count2)+"\n #_sel"+str(round(particlelist_selected2.shape[0]))+"\n Wmax"+str(round(np.nanmax(particlelist_weight2)))+"\n Wu: "+str(round(weightselection2/selectionfraction2))
#combine
particlelist_selected_combined=np.append(particlelist_selected,particlelist_selected2,axis=0)
[particlelist_selected_combined,particlelist_selected_combined_weight]=remove_doubles(particlelist_selected_combined,particlelist_selected_combined[:,2])
#plot
if plot_controloutput:
imgsize= gray.shape
fign=matplotlib.pyplot.figure(figsize=(15,15))
#fign.set_canvas(matplotlib.pyplot.gcf().canvas)
#fign.set_canvas(matplotlib.pyplot.gcf().canvas)
if plot_outputname=="":
ax1=fign.add_subplot(331)
ax2=fign.add_subplot(332)
ax3=fign.add_subplot(333)
ax4=fign.add_subplot(334)
ax5=fign.add_subplot(335)
ax6=fign.add_subplot(336)
ax7=fign.add_subplot(337)
ax8=fign.add_subplot(338)
ax9=fign.add_subplot(339)
fign2=matplotlib.pylab.Figure(figsize=(30,30))
axseparate=fign2.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax2.set_xticks([])
ax2.set_yticks([])
ax3.set_xticks([])
ax3.set_yticks([])
ax4.set_xticks([])
ax4.set_yticks([])
ax5.set_xticks([])
ax5.set_yticks([])
axseparate.set_xticks([])
axseparate.set_yticks([])
#plot image
ax1.set_ylim(0,imgsize[0])
ax1.set_xlim(0,imgsize[1])
ax2.set_ylim(0,imgsize[0])
ax2.set_xlim(0,imgsize[1])
ax3.set_ylim(0,imgsize[0])
ax3.set_xlim(0,imgsize[1])
ax4.set_ylim(0,imgsize[0])
ax4.set_xlim(0,imgsize[1])
ax5.set_ylim(0,imgsize[0])
ax5.set_xlim(0,imgsize[1])
axseparate.set_ylim(0,imgsize[0])
axseparate.set_xlim(0,imgsize[1])
else:
#gs = matplotlib.gridspec.GridSpec(4, 3)
gs = matplotlib.gridspec.GridSpec(4, 3,#numer rows, number colums
width_ratios=[1,1,1],
height_ratios=[1,1,0.5,0.5]
)
gs.update(wspace=0.4, hspace=0.4) #wspace left/right, hspace top/bottom
ax1mout = fign.add_subplot(gs[0:2, :])
ax2mout = fign.add_subplot(gs[2, 0])
ax3mout = fign.add_subplot(gs[2,1])
ax4mout = fign.add_subplot(gs[2,2])
ax2bmout = fign.add_subplot(gs[3, 0])
ax3bmout = fign.add_subplot(gs[3,1])
ax4bmout = fign.add_subplot(gs[3,2])
ax1mout.set_xticks([])
ax1mout.set_yticks([])
ax1mout.set_ylim(0,imgsize[0])
ax1mout.set_xlim(0,imgsize[1])
plot_annotatetext=plot_annotatetext+", cells: "+str(particlelist_selected.shape[0])
ax1mout.annotate(plot_annotatetext, xy=(0.,1.02),xycoords='axes fraction', color='k',fontsize=32)
ax1mout.annotate(strout1, xy=(1.01,0.8),xycoords='axes fraction', color='k',fontsize=20)
ax1mout.annotate(strout2, xy=(1.01,0.5),xycoords='axes fraction', color='k',fontsize=20)
ax2mout.set_xlabel("intensity")
ax3mout.set_xlabel("treshold")
ax4mout.set_xlabel("cluster weight")
ax2bmout.set_xlabel("intensity")
ax3bmout.set_xlabel("treshold")
ax4bmout.set_xlabel("cluster weight")
ax2mout.set_ylabel("abundance")
ax3mout.set_ylabel("# particles")
ax4mout.set_ylabel("abundance")
ax2bmout.set_ylabel("abundance")
ax3bmout.set_ylabel("# particles")
ax4bmout.set_ylabel("abundance")
ax2mout.annotate("adapted contrast method (all cells)", xy=(0.,1.05),xycoords='axes fraction', color='k',fontsize=20)
ax2bmout.annotate("average backround (only moving cells)", xy=(0.,1.05),xycoords='axes fraction', color='k',fontsize=20)
sizemarker=500
if plot_outputname=="":
ax1.imshow(gray)
ax2.imshow(gray,cmap='gray',vmin=0,vmax=255)
ax3.imshow(blurred_grayscale,cmap='gray',vmin=0,vmax=255)
axseparate.imshow(substracted)
#ax4.imshow(blurred_grayscale)
ax8.hist(gray.flatten(),bins=255,range=(0,256))#np.nanmax(gray)+1))
ax9.hist(substracted.flatten(),bins=256,range=(0,256))#np.nanmax(gray)+1))
#plot detected particles into
ax5.imshow(gray)
for ip in range(0,particlelist_selected.shape[0]):
ax5.scatter(particlelist_selected[ip,1],particlelist_selected[ip,0],s=sizemarker,edgecolors='w', facecolors='none')
ax4.scatter(particlelist_selected[ip,1],particlelist_selected[ip,0],s=sizemarker,edgecolors='w', facecolors='none')
axseparate.scatter(particlelist_selected[ip,1],particlelist_selected[ip,0],s=sizemarker,edgecolors='w', facecolors='none')
#facecolors='none', edgecolors='r'
ax7.plot(particlenum_treshold[:,0],particlenum_treshold[:,1])
ax7.set_xlim(0,np.nanmax(particlenum_treshold[:,0]))
ax7.set_ylim(0,1000)
ax7.axvline(tresholdconstant,color='k',ls='--')
ax6.hist(particlelist_weight,bins=100,range=(0,np.nanmax(particlelist_weight)))#np.nanmax(gray)+1))
ax6.axvline(weightselection,color='k',ls='--')
else:
ax1mout.imshow(gray_numpy_cutoff)
ax2mout.hist(gray.flatten(),bins=255,range=(0,256),color='red')#np.nanmax(gray)+1))
ax2mout.hist(substracted.flatten(),bins=256,range=(0,256),color='blue')#np.nanmax(gray)+1))
#ax2bmout.hist(gray2.flatten(),bins=255,range=(0,256),color='red')#np.nanmax(gray)+1))
ax2bmout.hist(substracted2.flatten(),bins=256,range=(0,256),color='blue')#np.nanmax(gray)+1))
for ip in range(0,particlelist_selected.shape[0]):
ax1mout.scatter(particlelist_selected[ip,1],particlelist_selected[ip,0],s=sizemarker,edgecolors='w', facecolors='none')
for ip in range(0,particlelist_selected2.shape[0]):
ax1mout.scatter(particlelist_selected2[ip,1],particlelist_selected2[ip,0],s=sizemarker,edgecolors='b', facecolors='none',linestyle=':')
if 3>4: #plot details
for ip in range(0,particlelist.shape[0]):
ax1mout.scatter(particlelist[ip,1],particlelist[ip,0],s=sizemarker*0.2,edgecolors='r', facecolors='none')
labeltext=str(particlelist_weight[ip])+", "+str(particlelist_size[ip])
print labeltext
ax1mout.text(particlelist[ip,1],particlelist[ip,0],labeltext)
#facecolors='none', edgecolors='r'
ax3mout.plot(particlenum_treshold[:,0],particlenum_treshold[:,1])
ax3mout.set_xlim(0,np.nanmax(particlenum_treshold[:,0]))
ax3mout.set_ylim(0,1000)
ax3mout.axvline(tresholdconstant,color='k',ls='--')
ax4mout.hist(particlelist_weight,bins=300,range=(0,10*weightselection))#np.nanmax(particlelist_weight)))#np.nanmax(gray)+1))
ax4mout.axvline(weightselection,color='k',ls='--')
ax3bmout.plot(particlenum_treshold2[:,0],particlenum_treshold2[:,1])
ax3bmout.set_xlim(0,np.nanmax(particlenum_treshold2[:,0]))
ax3bmout.set_ylim(0,1000)
ax3bmout.axvline(tresholdconstant2,color='k',ls='--')
ax4bmout.hist(particlelist_weight2,bins=300,range=(0,10*weightselection2))#np.nanmax(particlelist_weight2)))#np.nanmax(gray)+1))
ax4bmout.axvline(weightselection2,color='k',ls='--')
if plot_outputname=="":
fign.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95,hspace=.1,wspace=.1)#,wspace=5.0, hspace=.1)
figname="plot_detectedcells.png"
#fign.show()
#fign.draw()
fign.savefig(os.path.join(folder_detectiontest,figname))
fign2.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95,hspace=.1,wspace=.1)#,wspace=5.0, hspace=.1)
figname="plot_detectedcells_zoom.pdf"
fign2.savefig(os.path.join(folder_detectiontest,figname))
cv2.imwrite(os.path.join(folder_detectiontest,"testimage.jpg"),gray)
cv2.imwrite(os.path.join(folder_detectiontest,"testimage_substracted.jpg"),substracted)
else:
fign.subplots_adjust(left=0.1, bottom=0.07, right=0.95, top=0.95,hspace=.1,wspace=.1)#,wspace=5.0, hspace=.1)
figname=plot_outputname
#fign.show()
#fign.canvas.draw_idle()
fign.savefig(figname)
print plot_annotatetext.split(",")[0]
cv2.imwrite(os.path.join(folder_detectiontest,plot_annotatetext.split(",")[0].replace(": ","")+".jpg"),gray)
matplotlib.pylab.close()
return [particlelist_selected_combined,particlelist_selected,particlelist_selected2]
def analyze_movie(filenamein,framemaxin=2000,plot_detectionanalysis=True,num_avsteps=20, blur_parameter=20, selectionfraction=0.05, selectionfraction2="",short=False,min_value_selectionbackground=0,fulloutput=True,fluorescencedata=False):
if selectionfraction2=="":
selectionfraction2=selectionfraction
if short==True:
adds="_short"
else:
adds=""
movieoutputdir2=os.path.join(plot_controloutput,filenamein+"_detection"+adds)
if not os.path.exists(movieoutputdir2):
os.makedirs(movieoutputdir2)
else:
pass
filename=os.path.join(datafolderrawvideo2,filenamein)
#check if filename exists...
if os.path.exists(filename)==False:
filename=os.path.join(datafolderrawvideo1,filenamein)
if os.path.exists(filename)==False:
print "File not found: "+filename
errorfilenotfound
filenameinm=os.path.basename(filenamein[:-4])
filenameout=os.path.join(data_detection,filenameinm+adds+".npz")
filenameout_adaptedcontrast=os.path.join(data_detection,filenameinm+adds+"_adaptive.npz")
filenameout_background=os.path.join(data_detection,filenameinm+adds+"_background.npz")
filenameoutmat=filenameout[:-4]+adds+".mat"
filenameout_adaptedcontrastmat=filenameout_adaptedcontrast[:-4]+adds+".mat"
filenameout_backgroundmat=filenameout_background[:-4]+adds+".mat"
particlesdetect_list={}
particlesdetect_adaptedcontrast_list={}
particlesdetect_background_list={}
print "load avi file: "+filename
vc = cv2.VideoCapture(filename)
framecounter=0
length_movie = int(vc.get(cv2.CAP_PROP_FRAME_COUNT))
if length_movie<framemaxin:
framemaxin=length_movie
####load movie first time to calculate average
imglist=[]
if vc.isOpened():
rval , frame = vc.read()
imglist.append(frame)
else:
rval = False
if os.path.exists(filename)==False:
print "File not found: "+filename
here78
while rval:
if framecounter>num_avsteps:
break
#print framecounter
rval, frame = vc.read()
imglist.append(frame)
framecounter = framecounter + 1
#get image average
if fluorescencedata:
imgc_av=np.zeros([512,512,num_avsteps])
else:
imgc_av=np.zeros([1024,1280,num_avsteps])
for ila in range(0,num_avsteps):
imgc=imglist[ila].copy()
gray = cv2.cvtColor(imgc, cv2.COLOR_BGR2GRAY)
if fluorescencedata==False:
imgc_av[:,:,ila] = 255.-np.asarray(gray, dtype=float)
else:
imgc_av[:,:,ila] = np.asarray(gray, dtype=float)
imgc_avv=np.average(imgc_av,axis=2)
#end movie....close again....
#release memmory for avi file...
vc.release()
#load movie second time to detect cells
vc = cv2.VideoCapture(filename)
#make sure frame max is not too long...
framemaxinvideo = int(vc.get(cv2.CAP_PROP_FRAME_COUNT))
if framemaxinvideo-1<=framemaxin:
framemaxin=framemaxinvideo-2
framecounter=0
if vc.isOpened():
rval , frame = vc.read()
imgc=frame
else:
rval = False
while rval:
if framecounter>framemaxin:
break
print(framecounter)
rval, frame = vc.read()
imgc=frame
framecounter = framecounter + 1
#generate name (for movie)
framecounterstr=str(framecounter)
if framecounter<10:
mvstr="000"+framecounterstr
elif framecounter<100:
mvstr="00"+framecounterstr
elif framecounter<1000:
mvstr="0"+framecounterstr
else:
mvstr=""+framecounterstr
figname=mvstr+".jpg"
plot_annotatetext="frame: "+str(framecounter)+", time: "+str(framecounter/20.)+"s"
if plot_detectionanalysis==True:
plot_outputname_detection=os.path.join(movieoutputdir2,figname)
else:
plot_outputname_detection=""
[particlesdetect,particlesdetect_adaptedcontrast,particlesdetect_background]=detect_particles(imgc,imgc_avv,plot_controloutput=plot_detectionanalysis,plot_outputname=plot_outputname_detection,plot_annotatetext=plot_annotatetext,selectionfraction=selectionfraction,blur_parameter=blur_parameter,selectionfraction2=selectionfraction2,min_value_selectionbackground=min_value_selectionbackground,fluorescencedata=fluorescencedata)
#output particlesdetect is [numper particles, 3 (x,y,weight)]
particlesdetect_list["frame"+str(framecounter)]=particlesdetect
particlesdetect_adaptedcontrast_list["frame"+str(framecounter)]=particlesdetect_adaptedcontrast
particlesdetect_background_list["frame"+str(framecounter)]=particlesdetect_background
#release memmory for avi file...
vc.release()
#save detected cells
diroutc=os.path.dirname(filenameout)
if not os.path.exists(diroutc):
os.makedirs(diroutc)
else:
pass
np.savez(filenameout,**particlesdetect_list)
if fulloutput==True:
np.savez(filenameout_adaptedcontrast,**particlesdetect_adaptedcontrast_list)
np.savez(filenameout_background,**particlesdetect_background_list)
if fulloutput==True:
convert_detectedcellsintomat(particlesdetect_list,filenameoutmat)
convert_detectedcellsintomat(particlesdetect_adaptedcontrast_list,filenameout_adaptedcontrastmat)
convert_detectedcellsintomat(particlesdetect_background_list,filenameout_backgroundmat)
if plot_detectionanalysis:
filenameoutdetmovie=filenameout[:-4].split('/')[-1]
name_movieoutis=os.path.join(data_movieoutput,"movie_detection_"+filenameoutdetmovie+".mp4")
opt_movie_fps=20
process_name ="ffmpeg -y -r "+ str(opt_movie_fps)+" -pattern_type glob -i '"+os.path.join(movieoutputdir2, "*.jpg'")+" -c:v libx264 -pix_fmt yuv420p "+name_movieoutis
subprocess.call(process_name, shell=True)
print ("detection movie saved to: "+name_movieoutis)
print("data detected cells saved to "+filenameout)
#if matlab file is wanted
def convert_detectedcellsintomat(listin,filenout):
numt=len(listin)
FrameStack = np.empty((numt-1,3,), dtype=np.object)
for i in range(numt-1):
#print "frame"+str(i+1)
x=listin["frame"+str(i+1)].copy()[:,0:2]+0.01
x[:,1]=0
#print str(np.nanmax(x))+" "+str(np.nanmin(x[:,0]))
y=listin["frame"+str(i+1)].copy()[:,0:2]
y[:,0]=listin["frame"+str(i+1)][:,1]+0.01
y[:,1]=0
weight=listin["frame"+str(i+1)].copy()[:,0:2]
weight[:,1]=0
weight[:,0]=listin["frame"+str(i+1)][:,2]
FrameStack[i,0] = x
FrameStack[i,1] = y
FrameStack[i,2] = weight
scipy.io.savemat(filenout, {"movieInfoCell":FrameStack})
#merge trajectories
def mergetrajectory(trj_xdata,trj_ydata,mergdistance=20.):
num_traj=trj_xdata.shape[0] #trajectories and duration
deleterows=[]
print "num traj before merging"
print num_traj
#merge trajectories
for il in range(num_traj-1,-1,-1):
#find where trajectory begins....
valuesc= np.isfinite(trj_ydata[il,:])
indt=np.argwhere(valuesc==True)[0][0]
if indt<3:
break
xc1=trj_xdata[il,indt]
yc1=trj_ydata[il,indt]
#go through other trajectories and check if they end here
for il2 in range(il-1,-1,-1):
#check if il2 is nan
if np.isnan(trj_xdata[il2,indt]):
#check if timepoint indt-1 is number
if np.isfinite(trj_xdata[il2,indt-1]):
xc2=trj_xdata[il2,indt-1]
yc2=trj_ydata[il2,indt-1]
distance=np.sqrt(np.power(xc2-xc1,2.)+np.power(yc2-yc1,2.))
if(distance<mergdistance):
trj_xdata[il,:indt-1]=trj_xdata[il2,:indt-1]
trj_ydata[il,:indt-1]=trj_ydata[il2,:indt-1]
"merging2 "+str(il2)
trj_xdata[il,:]
deleterows.append(il2)
break
#check if timepoint indt-1 is number
elif np.isfinite(trj_xdata[il2,indt-2]):
xc2=trj_xdata[il2,indt-2]
yc2=trj_ydata[il2,indt-2]
distance=np.sqrt(np.power(xc2-xc1,2.)+np.power(yc2-yc1,2.))
if(distance<mergdistance):
trj_xdata[il,:indt-2]=trj_xdata[il2,:indt-2]
trj_ydata[il,:indt-2]=trj_ydata[il2,:indt-2]
"merging2 "+str(il2)
deleterows.append(il2)
break
#check if timepoint indt-1 is number
elif np.isfinite(trj_xdata[il2,indt-3]):
xc2=trj_xdata[il2,indt-3]
yc2=trj_ydata[il2,indt-3]
distance=np.sqrt(np.power(xc2-xc1,2.)+np.power(yc2-yc1,2.))
if(distance<mergdistance):
trj_xdata[il,:indt-3]=trj_xdata[il2,:indt-3]
trj_ydata[il,:indt-3]=trj_ydata[il2,:indt-3]
"merging3 "+str(il2)
deleterows.append(il2)
break
#check if il2-2 is number
#delete
trj_xdata=np.delete(trj_xdata,deleterows,axis=0)
trj_ydata=np.delete(trj_ydata,deleterows,axis=0)
# x = numpy.delete(x,(2), axis=1)
return [trj_xdata,trj_ydata]
def generate_movie(filenamein,plot_detectedcells=True,plot_trajectories=False,framemaxin=2000,trajectory_color='trajectories'):
if filenamein[-4:]==".avi":
filenamein=filenamein[:-4]
filenameinbase=os.path.basename(filenamein)
#load avi file using imagej
movieoutputdir=os.path.join(plot_controloutput,filenamein)
if not os.path.exists(movieoutputdir):
os.makedirs(movieoutputdir)
else:
pass
movieoutputdir2=os.path.join(plot_controloutput,filenamein+"_detection")
if not os.path.exists(movieoutputdir2):
os.makedirs(movieoutputdir2)
else:
pass
try:
filename=os.path.join(datafolderrawvideo2,filenamein+".avi")
except:
filename=os.path.join(datafolderrawvideo,filenamein+".avi")
print os.path.join(datafolderrawvideo,filenamein+".avi")
haeh
print "load avi file: "+filename
vc = cv2.VideoCapture(filename)
length = int(vc.get(cv2.CAP_PROP_FRAME_COUNT))
print length
framecounter=1
if vc.isOpened():
rval , frame = vc.read()
imgc=frame
else:
rval = False
if os.path.exists(filename)==False:
print "File not found: "+filename
here78
#load detected trajectories
if plot_trajectories:
filenametrj=os.path.join(data_trajectories,filenameinbase+".npy")
trj_data=np.load(filenametrj)
num_traj=trj_data.shape[0]
num_trjovertime=np.zeros([trj_data.shape[1]])
trajectorylength=np.zeros([num_traj])
for it in range(0,num_traj):
trajectorylength[it]=np.count_nonzero(~np.isnan(trj_data[it,:,0]))
for it in range(0,trj_data.shape[1]):
num_trjovertime[it]=np.count_nonzero(~np.isnan(trj_data[:,it,0]))
#0 index
#1 x
#2 y
#3 time
#4 velocity
#5 theta
#6 tubmling event....
#7 theta
#8 tubmling event....
#get ranges
vmin=np.nanmin(trj_data[:,:,4])
vmax=np.nanmax(trj_data[:,:,4])
dvmin=np.nanmin(trj_data[:,:,5])
dvmax=np.nanmax(trj_data[:,:,5])
dthetamin=np.nanmin(trj_data[:,:,7])
dthetamax=np.nanmax(trj_data[:,:,7])
#load detected particles...
if plot_detectedcells:
filenamedetection=os.path.join(data_detection,filenamein+".npz")
filenamedetection_adaptive=os.path.join(data_detection,filenamein+"_adaptive.npz")
filenamedetection_background=os.path.join(data_detection,filenamein+"_background.npz")
detected=np.load(filenamedetection)
detected_adaptive=np.load(filenamedetection_adaptive)
detected_background=np.load(filenamedetection_background)
while rval:
if framecounter>framemaxin:
break
print framecounter
rval, frame = vc.read()
imgc=frame
framecounter = framecounter + 1
gray = cv2.cvtColor(imgc, cv2.COLOR_BGR2GRAY)
#go through every frame....
framecounterstr=str(framecounter)
if framecounter<10:
mvstr="000"+framecounterstr
elif framecounter<100:
mvstr="00"+framecounterstr
elif framecounter<1000:
mvstr="0"+framecounterstr
else:
mvstr=""+framecounterstr
figname=mvstr+".jpg"
fign=figure(figsize=(20,12))
gs = matplotlib.gridspec.GridSpec(2, 3,#numer rows, number colums
width_ratios=[1,1,0.1],
height_ratios=[1,0.5]
)
gs.update(wspace=0.4, hspace=0.4) #wspace left/right, hspace top/bottom
ax1=fign.add_subplot(gs[0, 0])
ax2=fign.add_subplot(gs[0, 1])
ax3=fign.add_subplot(gs[1,0])
if trajectory_color in ["speed","acceleration","dtheta"]:
ax2c=fign.add_subplot(gs[0,2])
cb=matplotlib.colorbar.ColorbarBase(ax2c, cmap=cm.jet)
cb.set_ticks([0,vmax/2.,vmax])
ax1.set_xticks([])
ax1.set_yticks([])
ax2.set_xticks([])
ax2.set_yticks([])
imgsize= imgc.shape
#plot image
ax1.set_ylim(0,imgsize[0])
ax1.set_xlim(0,imgsize[1])
ax2.set_ylim(0,imgsize[0])
ax2.set_xlim(0,imgsize[1])
ax1.imshow(gray)
if plot_detectedcells:
plot_annotatetext="frame: "+str(framecounter)+", time: "+str(framecounter/20.)+"s"
try:
xc=detected["frame"+str(framecounter-1)][:,0]
yc=detected["frame"+str(framecounter-1)][:,1]
except:
"cell detection not found"
xc[:]=np.nan
yc[:]=np.nan
detected=np.load(filenamedetection)
detected_adaptive=np.load(filenamedetection_adaptive)
detected_background=np.load(filenamedetection_background)
try:
xc_background=detected_background["frame"+str(framecounter-1)][:,0]