/
Myxo_Track.py
executable file
·593 lines (466 loc) · 14.8 KB
/
Myxo_Track.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
from ij import ImageStack, ImagePlus, WindowManager, IJ
from ij.gui import Roi, NonBlockingGenericDialog, Overlay, ImageRoi, Line, OvalRoi, PolygonRoi, ShapeRoi, TextRoi, EllipseRoi
from ij.process import ImageProcessor, ShortProcessor, ByteProcessor
from ij.plugin.frame import RoiManager
from ij.text import TextWindow
from ij.plugin import Straightener, Duplicator, ZProjector, MontageMaker, ImageCalculator, RGBStackMerge
from ij.measure import ResultsTable
from java.awt import TextField, Panel, GridLayout, ComponentOrientation, Label, Checkbox, BorderLayout, Button, Color, Font, Rectangle, Polygon
from java.lang import Double,Boolean,Float
from java.awt.event import MouseAdapter,MouseEvent
from java.awt import Point, Color, Font
from javax.swing import JOptionPane,JFrame, JPanel
import sys
import os
import time
import glob
import os.path as path
import getpass
import shutil
import random
username=getpass.getuser()
#mypath=os.path.expanduser(IJ.getDirectory("plugins")+"MeasureCells")
mypath=os.path.expanduser(os.path.join("~","Dropbox","MacrosDropBox","py","MorphoBactProject"))
sys.path.append(mypath)
from org.python.core import codecs
codecs.setDefaultEncoding('utf-8')
from MorphoBact import Morph
from BacteriaCell import Bacteria_Cell
from CellsSelection import CellsSelection
imp=IJ.getImage()
hs=3
sw=1
#Color.blue, Color.green, Color.magenta, Color.orange, Color.yellow
#red=Color(255,0,0)
#green=Color(0,255,0)
IJ.showMessage("Select the folder 'Cells' containing the cells to import")
selectdir=IJ.getDirectory("image")
selectdir=IJ.getDirectory("")
#pathdir=str(selectdir).rsplit("/", 2)[0]+"/ROIs/"
pathdir=os.path.join(os.path.split(os.path.split(selectdir)[0])[0], "ROIs", "")
#rootdir=str(selectdir).rsplit("/", 2)[0]+"/"
rootdir=os.path.join(os.path.split(os.path.split(selectdir)[0])[0], "")
listfilescells=[]
listrois=[]
listfilescells.extend(glob.glob(selectdir+"*"))
listrois.extend(glob.glob(pathdir+"*"))
#allcells=[]
allcellnames=[]
for cellfile in listfilescells :
#allcells.append(Bacteria_Cell.makeCell(cellfile))
#name=cellfile.rsplit("/", 1)[1][:-len(".cell")]
name=os.path.splitext(os.path.split(cellfile)[1])[0]
#allcellnames.append(allcells[-1].getName())
allcellnames.append(name)
dictRois={}
for r in listrois :
#cle=r.rsplit("/", 1)[1][:-len(".zip")]
cle=os.path.splitext(os.path.split(r)[1])[0]
if cle in allcellnames : dictRois[cle]=r
rm = RoiManager.getInstance()
if (rm==None): rm = RoiManager()
rm.runCommand("UseNames", "true")
rm.runCommand("Associate", "true")
rm.runCommand("Show None")
gw = CellsSelection()
gw.setTitle(imp.getTitle())
gw.run(dictRois.keys(), pathdir)
gw.show()
gw.setSelected(dictRois.keys())
while not gw.oked and gw.isShowing() :
gw.setLabel("Validate selection with OK !!")
listcellname = list(gw.getSelected())
gw.resetok()
gw.setLabel("...")
gw.hide()
rm.runCommand("reset")
if imp.getOverlay() is not None : imp.getOverlay().clear()
overlay=Overlay()
imp.setOverlay(overlay)
gd0=NonBlockingGenericDialog("settings")
gd0.addCheckbox("Show the overlay during the process ? (slow option)", False)
gd0.addNumericField("Minimal Lifetime : ",10,0)
gd0.addNumericField("Minimal distance to reversion : ",4,0)
gd0.addNumericField("Sub sampling ? : ",1,0)
gd0.addNumericField("Radius for fluo tracking ? : ",8,0)
gd0.showDialog()
isShow = gd0.getNextBoolean()
minLife = gd0.getNextNumber()
mind = gd0.getNextNumber()
subs = gd0.getNextNumber()
rayon = gd0.getNextNumber()
if gd0.wasCanceled() :
isShow = True
imp.show()
else :
if isShow : imp.show()
else : imp.hide()
dicSens, dicSpeed, dicAngle, dicCumuld, dicPos, dicFluoA, dicFluoB ={},{},{},{},{},{},{}
dicSpeedA, dicSpeedB, dicSpeedC, dicMidAxis, dicFeret = {},{},{},{},{}
maxx=-1
maxspeed=-1
maxcumuld=-1
colors = []
ncells= len(listfilescells)
if ncells > 0 :
step=200/ncells
if step<1 : step=1
for i in range(ncells) :
r = random.randrange(5,205,step)
g = random.randrange(10,210,step)
b = random.randrange(30,230,step)
colors.append(Color(r, g, b))
if isShow : imp.show()
else : imp.hide()
cles=[]
now = time.strftime('%d-%m-%y_%Hh%Mm%Ss',time.localtime())
IJ.log("-------start at "+now+" ------")
#for cell in listfilescells :
f1 = open(rootdir+now+"-R1-MT.txt", "w")
tab="\t"
f1.write("cell"+tab+"maxFrames"+tab+"maxcumul"+tab+"nrevs"+"\n")
for cle in listcellname :
rm.runCommand("reset")
#cle = cell.rsplit("/", 1)[1][:-len(".cell")]
#cles.append(cle)
rm.runCommand("Open", dictRois[cle])
rm.runCommand("Show None")
RawroisArray=rm.getRoisAsArray()
if len(RawroisArray)< minLife : continue
roisArray=[RawroisArray[i] for i in range(0,len(RawroisArray), subs)]
IJ.showStatus(cle)
IJ.showProgress(listcellname.index(cle), len(listcellname))
dxA=[]
dyA=[]
dxB=[]
dyB=[]
dA=[]
dB=[]
sensA = 1
sensB = -1
nrev = 0
color=colors.pop(0)
colorA=color.brighter()
colorB=color.darker()
r=colorA.getRed()
g=colorA.getGreen()
b=colorA.getBlue()
reversions, speed, angles, cumuld, pos, fluoA, fluoB = [sensA],[0],[0], [0], [], [], []
speedA, speedB, speedC = [0],[0], [(0,0)]
midaxislength = []
Feret = []
pointsA={}
pointsB={}
pointsC={}
pointsD={}
centres={}
i0 = roisArray[0].getPosition()
end = roisArray[-1].getPosition()
imp.setSlice(i0)
t=Morph(imp, roisArray[0])
midline = t.MidAxis
try : polygon=midline.getFloatPolygon()
except AttributeError :
print "break at", cle, i
break
#xpoints = Morph(imp, roisArray[0]).MidAxis.getPolygon().xpoints
#ypoints = Morph(imp, roisArray[0]).MidAxis.getPolygon().ypoints
#npoints = Morph(imp, roisArray[0]).MidAxis.getPolygon().npoints
xpoints = polygon.xpoints
ypoints = polygon.ypoints
npoints = polygon.npoints
midaxislength.append(npoints)
Feret.append(t.MaxFeret)
ci = len(xpoints)//2
centres[0]=(xpoints[ci], ypoints[ci])
pos.append(centres[0])
pointsA[0]=(xpoints[0], ypoints[0])
pointsB[0]=(xpoints[-1], ypoints[-1])
pointsC[0]=(xpoints[1], ypoints[1])
pointsD[0] = (xpoints[-2], ypoints[-2])
for i in range(1, len(roisArray), 1) :
IJ.showProgress(i, len(roisArray))
imp.setSlice(i+i0)
t=Morph(imp, roisArray[i])
#print cle, i, t.MidAxis
#try : xpoints = t.MidAxis.getPolygon()
#except AttributeError :
# print "break"
# break
midline=t.MidAxis
try : polygon=midline.getFloatPolygon()
except AttributeError :
print "break at", cle, i
break
xpoints = polygon.xpoints
ypoints = polygon.ypoints
npoints = polygon.npoints
midaxislength.append(npoints)
Feret.append(t.MaxFeret)
#xpoints = t.MidAxis.getPolygon().xpoints
#ypoints = t.MidAxis.getPolygon().ypoints
#npoints = t.MidAxis.getPolygon().npoints
ci = len(xpoints)//2
centres[i]=(xpoints[ci], ypoints[ci])
pos.append(centres[i])
# chgt repere pour centroide
x0=pointsA[i-1][0]-centres[i-1][0]
y0=pointsA[i-1][1]-centres[i-1][1]
x1=xpoints[0]-centres[i][0]
y1=ypoints[0]-centres[i][1]
x2=xpoints[-1]-centres[i][0]
y2=ypoints[-1]-centres[i][1]
d1=Morph.distMorph([(1,x0,x1),(1, y0, y1)]) # dist from old A to new extem1
d2=Morph.distMorph([(1,x0,x2),(1, y0, y2)])# dist from old A to new extem2
if d1<=d2 :
pointsA[i]=(xpoints[0], ypoints[0]) # new A is the closest from old A
pointsB[i]=(xpoints[-1], ypoints[-1])
pointsC[i]=(xpoints[1], ypoints[1])
pointsD[i]=(xpoints[-2], ypoints[-2])
else :
pointsB[i]=(xpoints[0], ypoints[0])
pointsA[i]=(xpoints[-1], ypoints[-1]) # new A is the closest from old A
pointsC[i]=(xpoints[-2], ypoints[-2])
pointsD[i]=(xpoints[1], ypoints[1])
# ------- coordonees image ------------
xa0=pointsA[i-1][0]
xa1=pointsA[i][0]
ya0=pointsA[i-1][1]
ya1=pointsA[i][1]
xb0=pointsB[i-1][0]
xb1=pointsB[i][0]
yb0=pointsB[i-1][1]
yb1=pointsB[i][1]
xc0=centres[i-1][0]
yc0=centres[i-1][1]
xc1=centres[i][0]
yc1=centres[i][1]
# -------- fluo poles par l'axe ---
# -------- fluo poles --------------
polAx0 = xa1 - rayon
polAx1 = xa1 + rayon
polAy0 = ya1 - rayon
polAy1 = ya1 + rayon
polBx0 = xb1 - rayon
polBx1 = xb1 + rayon
polBy0 = yb1 - rayon
polBy1 = yb1 + rayon
polA = EllipseRoi(polAx0, polAy0, polAx1, polAy1, 1)
polB = EllipseRoi(polBx0, polBy0, polBx1, polBy1, 1)
imp.setRoi(polA)
#overlay.add(polA)
ipA = imp.getProcessor()
isA = ipA.getStatistics()
imp.setRoi(polB)
#overlay.add(polB)
ipB = imp.getProcessor()
isB = ipB.getStatistics()
fluoA.append(isA.max)
fluoB.append(isB.max)
# -------- end fluo poles --------------
# ------------ coordonees old centre -----------
vC1=(xc1-xc0, yc0-yc1)
speedC.append(vC1)
#methode centres :
dc=Morph.distMorph([(1, xc0, xc1),(1, yc0, yc1)])
speed.append(dc)
if dc>mind :
da=Morph.distMorph([(1, xa1, xc0),(1, ya1, yc0)])
db=Morph.distMorph([(1, xb1, xc0),(1, yb1, yc0)])
if da>=db :
#sens.append("A")
reversions.append(sensA)
else :
#sens.append("B")
reversions.append(sensB)
if i==1 : reversions[0] = sensB
else :
if reversions[-1]==sensA : reversions.append(sensA)
else : reversions.append(sensB)
if reversions[-2]*reversions[-1]<1 : nrev+=1
#---- end centres
if reversions[-1]==sensA :
ar=Arrow(xa0,ya0, xa1,ya1)
#ar.setStrokeColor(Color.green)
ar.setStrokeColor(colorA)
ar.setStrokeWidth(sw)
ar.setHeadSize(hs)
overlay.add(ar)
else :
ar=Arrow(xb0,yb0, xb1,yb1)
#ar.setStrokeColor(Color.red)
ar.setStrokeColor(colorB)
ar.setStrokeWidth(sw)
ar.setHeadSize(hs)
overlay.add(ar)
#speed.append(Morph.distMorph([(1, centres[i-1][0], centres[i][0]),(1, centres[i-1][1], centres[i][1])]))
#angles.append(t.AngleFeret)
cumuld.append(cumuld[-1]+speed[-1])
#time.sleep(0.2)
else : cles.append(cle)
speedA.append(0)
speedB.append(0)
#------- premier point de la fluo
polAx0 = pointsA[0][0] -rayon
polAx1 = pointsA[0][0] + rayon
polAy0 = pointsA[0][1] - rayon
polAy1 = pointsA[0][1] + rayon
polBx0 = pointsB[0][0] - rayon
polBx1 = pointsB[0][0] + rayon
polBy0 = pointsB[0][1] - rayon
polBy1 = pointsB[0][1] + rayon
polA = EllipseRoi(polAx0, polAy0, polAx1, polAy1, 1)
polB = EllipseRoi(polBx0, polBy0, polBx1, polBy1, 1)
imp.setSlice(i0)
imp.setRoi(polA)
overlay.add(polA)
ipA = imp.getProcessor()
isA = ipA.getStatistics()
imp.setSlice(i0)
imp.setRoi(polB)
overlay.add(polB)
ipB = imp.getProcessor()
isB = ipB.getStatistics()
fluoA.insert(0,isA.max)
fluoB.insert(0,isB.max)
# ----- fin dernier point de la fluo
for i in range(2,len(pointsA)) :
speedA.append((pointsA[i-1][0]-pointsA[i-2][0])*(pointsA[i][0]-pointsA[i-1][0])+(pointsA[i-2][1]-pointsA[i-1][1])*(pointsA[i-1][1]-pointsA[i][1])) #scalaire a0a1Xa1a2
speedB.append((pointsB[i-1][0]-pointsB[i-2][0])*(pointsB[i][0]-pointsB[i-1][0])+(pointsB[i-2][1]-pointsB[i-1][1])*(pointsB[i-1][1]-pointsB[i][1]))
dicSens[cle]=reversions
dicSpeed[cle]=speed
dicSpeedA[cle]=speedA
dicSpeedB[cle]=speedB
dicSpeedC[cle]=speedC
dicMidAxis[cle]=midaxislength
dicFeret[cle] = Feret
dicCumuld[cle]=cumuld
dicPos[cle]=pos
dicFluoA[cle]=fluoA
dicFluoB[cle]=fluoB
if i > maxx : maxx = i+1
if max(speed) > maxspeed : maxspeed = max(speed)
if max(cumuld) > maxcumuld : maxcumuld = max(cumuld)
tab="\t"
if cle in cles :
IJ.log(cle+tab+str(len(reversions))+tab+str(max(cumuld))+tab+str(nrev))
f1.write(cle+tab+str(len(reversions))+tab+str(max(cumuld))+tab+str(nrev)+"\n")
del(reversions)
del(speed)
del(speedA)
del(speedB)
del(speedC)
del(midaxislength)
del(Feret)
del(cumuld)
del(pos)
del(fluoA)
del(fluoB)
IJ.log("-------end-------")
IJ.log(str(len(cles))+" cells")
f1.close()
for cle in cles :
reversions, speed, speedA, speedB, speedC, cumuld, fluoA, fluoB = dicSens[cle], dicSpeed[cle], dicSpeedA[cle], dicSpeedB[cle], dicSpeedC[cle], dicCumuld[cle], dicFluoA[cle], dicFluoB[cle]
midaxislength = dicMidAxis[cle]
Feret = dicFeret[cle]
for i in range(maxx-len(reversions)) :
reversions.append(Double.NaN)
speed.append(Double.NaN)
speedA.append(Double.NaN)
speedB.append(Double.NaN)
speedC.append((Double.NaN,Double.NaN))
midaxislength.append(Double.NaN)
Feret.append(Double.NaN)
cumuld.append(Double.NaN)
fluoA.append(Double.NaN)
fluoB.append(Double.NaN)
# plot1=Plot("Reversions-"+cle,"frames","",range(1,maxx+1),reversions)
# plot1.setLimits(0,maxx+1,-1.1,1.1)
#
# ip1=plot1.getProcessor()
# ip1.invert()
# implot1=ImagePlus("plot1", ip1)
#
# istack=ImageStack(ip1.getWidth(), ip1.getHeight())
# istack.addSlice("reversions", ip1)
#
# plot2=Plot("Speed-"+cle,"","",range(1,maxx+1),speed)
# plot2.setLimits(0,maxx+1,0,maxspeed*1.1)
# ip2=plot2.getProcessor()
# ip2.invert()
# implot2=ImagePlus("plot2", ip2)
#
# istack.addSlice("speed", ip2)
#
# plot3=Plot("CumulDist-"+cle,"","",range(1,maxx+1),cumuld)
# plot3.setLimits(0,maxx+1,0,maxcumuld*1.1)
# ip3=plot3.getProcessor()
# ip3.invert()
# implot3=ImagePlus("plot3", ip3)
#
# istack.addSlice("cumul", ip3)
# imstack=ImagePlus("stack3", istack)
#
# imstack.show()
# IJ.selectWindow("stack3")
#
# IJ.run("Stack to RGB", "")
# lastimage=IJ.getImage()
# imstack.close()
#
# cp = lastimage.getProcessor()
# try : rgbstack.addSlice(cle, cp)
# except NameError :
# rgbstack = lastimage.createEmptyStack()
# rgbstack.addSlice(cle, cp)
# lastimage.close()
del(reversions)
del(speed)
del(cumuld)
#imprgb=ImagePlus("rgbStack", rgbstack)
#imprgb.show()
#IJ.selectWindow("rgbStack")
#IJ.run("Hide Overlay", "")
imp.show()
IJ.selectWindow(imp.getTitle())
imp.setOverlay(overlay)
IJ.run("Show Overlay", "")
for i in range(len(cles)) :
pos=dicPos[cles[i]]
command = 'Overlay.drawString("'+cles[i]+'", '+str(pos[0][0])+', '+str(pos[0][1])+')'
IJ.runMacro(command)
f2 = open(rootdir+now+"-R2-MT.txt", "w")
f3 = open(rootdir+now+"-R3-MT.txt", "w")
f4 = open(rootdir+now+"-R4-MT.txt", "w")
tab="\t"
line2 = ["sens"+cle+tab+"speed"+cle+tab+"cumul"+cle+tab+"fluoA"+cle+tab+"fluoB"+cle for cle in cles]
line3 = ["scalA"+cle+tab+"scalB"+cle+tab+"oriX"+cle+tab+"oriY"+cle for cle in cles]
line4 = ["midaxis"+cle+tab+"Feret"+cle+tab+"fluoA"+cle+tab+"fluoB"+cle for cle in cles]
f2.write(tab.join(line2)+"\n")
f3.write(tab.join(line3)+"\n")
f4.write(tab.join(line4)+"\n")
for i in range(maxx) :
line2 = [str(dicSens[cle][i])+tab+str(dicSpeed[cle][i])+tab+str(dicCumuld[cle][i])+tab+str(dicFluoA[cle][i])+tab+str(dicFluoB[cle][i]) for cle in cles]
line3 = [str(dicSpeedA[cle][i])+tab+str(dicSpeedB[cle][i])+tab+str(dicSpeedC[cle][i][0])+tab+str(dicSpeedC[cle][i][1]) for cle in cles]
line4 = [str(dicMidAxis[cle][i])+tab+str(dicFeret[cle][i])+tab+str(dicFluoA[cle][i])+tab+str(dicFluoB[cle][i]) for cle in cles]
f2 .write(tab.join(line2)+"\n")
f3 .write(tab.join(line3)+"\n")
f4.write(tab.join(line4)+"\n")
#print i, line
f2.close()
f3.close()
f4.close()
dictRois.clear()
for r in listrois :
cle=os.path.splitext(os.path.split(r)[1])[0]
if cle in cles : dictRois[cle]=r
gw = CellsSelection()
gw.setTitle(imp.getTitle())
gw.run(dictRois.keys(), pathdir)
gw.show()
gw.setSelected(dictRois.keys())
while not gw.oked and gw.isShowing() :
pass
gw.resetok()
gw.setLabel("...")
gw.hide()