-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtrackingFunctions.py
1883 lines (1401 loc) · 78.5 KB
/
trackingFunctions.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
# by Facundo Sosa-Rey, 2021. MIT license
from matplotlib import patches
from scipy.spatial import KDTree as KDTree
import numpy as np
import viscid as vs
import cv2 as cv
from skimage import morphology
import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib.patches as mpatches
from centroid import centroidObj
from random import shuffle
import multiprocessing
def unique(myList):
#elements added to set only once, removes repetitions
return np.array(list(set(myList)))
def randomizeVoxelSlice(V_fiberMap,listMarkers,exclusionList):
V_fiberMap_randomized=V_fiberMap.copy()
reassignedMarkers=listMarkers.copy()
#random shuffling of original markers
shuffle(reassignedMarkers)
markerLUT={}
for i,iMark in enumerate(listMarkers):
markerLUT[iMark]=reassignedMarkers[i]
V_fiberMap_randomized=compactifySlice(
V_fiberMap,
markerLUT,
exclusionList
)
return V_fiberMap_randomized
def compactifySlice(slice,compactifyIDs_LUT,exclusionList):
sliceCompactified=np.ones(slice.shape,np.int32)*-1
for ix in range(len(slice)):
for iy in range(len(slice[0])):
if slice[ix,iy] not in exclusionList:
sliceCompactified[ix,iy]=compactifyIDs_LUT[slice[ix,iy]]
return sliceCompactified
def stitchingRanking(presentMatchDataTuple,candidateMatchDataTuple):
if len(presentMatchDataTuple)==2: #blindStitching
presentMatchDistance =presentMatchDataTuple [0]
candidateMatchDistance =candidateMatchDataTuple[0]
keepNewMatch=False
if candidateMatchDistance<presentMatchDistance:
keepNewMatch=True
elif candidateMatchDistance==presentMatchDistance:
#edge case where total dist is the same
presentLateralDist =presentMatchDataTuple [1]
candidateLateralDist =candidateMatchDataTuple[1]
if candidateLateralDist<presentLateralDist:
keepNewMatch=True
return keepNewMatch
if len(presentMatchDataTuple)==4: #smartStitching
presentLength_up = presentMatchDataTuple [2]
candidateLength_up = candidateMatchDataTuple[2]
presentAngleOrienVec = np.degrees(np.arccos( presentMatchDataTuple[3]))
candidateAngleOrienVec = np.degrees(np.arccos(candidateMatchDataTuple[3]))
keepNewMatch=False
if candidateLength_up>presentLength_up:
if presentAngleOrienVec==candidateAngleOrienVec:
#edge case where stitching occurs twice from same fiber pairs, (both pairs of endpoints pass stitching criteria)
presentMatchDistance =presentMatchDataTuple [0]
candidateMatchDistance =candidateMatchDataTuple[0]
if candidateMatchDistance<presentMatchDistance:
keepNewMatch=True
else:
#the angles between segments can be increase by as much as 5 degrees, if the candidate extension is longer than the current
if -5.<(presentAngleOrienVec-candidateAngleOrienVec)<5.:
keepNewMatch=True
elif candidateAngleOrienVec<presentAngleOrienVec:
keepNewMatch=True
return keepNewMatch
class knn3D:
#this class store the KD tree for the blind stitching procedure
def __init__(self,topCenters):
# build kd-tree
self.topCenters=topCenters
self.tree_down=KDTree(topCenters)
def query(self,
bottomCenters,
distTotal,
distLateral=None,
angleMax=None,
backTrackingLimit=0.,
lengths=None,
k=1,
suffixCheck=None
):
"""search the kd-tree, return correspondance between bottomCenters[id_bottom] to topCenters[id_top]
that satisfy
:total (Euclidian) distance<distTotal ,
:lateral (in plane) distance<distLateral (if present),
:angle between segments<angleMax,
:backtracking distance<backTrackingLimit
For smartStitching, lengths are passed to rank order the candidate matches
For stitching across combinations, suffix in [0.123,0.132,0.321] are passed
to prevent matching from the same permutation.
"""
# id_down: topCenter[id_down[i]] is closest to bottomCenters[i], with distance d_down[i]
[d_down, id_down] = self.tree_down.query(bottomCenters,k=k)
# build kd-tree
tree_up = KDTree(bottomCenters)
# search the kd-tree
# id_up: bottomCenter[id_up[i]] is closest to topCenters[i], with distance d_up[i]
[d_up, id_up] = tree_up.query(self.topCenters,k=k)
matches={}
matches["listCentersTop"]={}
matchesBackup={}
matchesBackup["listCentersTop"]={}
if suffixCheck is not None:
in123_bottom=suffixCheck[0]
in123_top =suffixCheck[1]
in132_bottom=suffixCheck[2]
in132_top =suffixCheck[3]
in321_bottom=suffixCheck[4]
in321_top =suffixCheck[5]
if k!=1:
d_downList=[]
id_downList=[]
d_upList =[]
id_upList =[]
for iCandidateDown in range(len(id_down)):
if any(d_down[iCandidateDown]<distTotal):
if suffixCheck is None:
# check if below max distance and prevent self-matching
id_downList=[val for val in id_down[iCandidateDown][d_down[iCandidateDown]<distTotal] if val!=iCandidateDown]
else:
# check if below max distance and prevent self-matching
id_downList=[
val for val in id_down[iCandidateDown][d_down[iCandidateDown]<distTotal]\
if val!=iCandidateDown and \
not np.logical_and(in123_bottom[iCandidateDown],in123_top[val]) and \
not np.logical_and(in132_bottom[iCandidateDown],in132_top[val]) and \
not np.logical_and(in321_bottom[iCandidateDown],in321_top[val])
]
# bidirectional match is required:
for iCandidateUp in id_downList:
# if match exist from A->B, B->A will also work, to the possible detriment of B->C
# (can happen in combinePermutations)
if not(iCandidateUp in matches.keys() and matches[iCandidateUp][0]==iCandidateDown):
id_upList=id_up[iCandidateUp][d_up[iCandidateUp]<distTotal]
if any(id_upList==iCandidateDown):
successfulMatch=False
#check if backtracking lmit is not exceeded:
if self.topCenters[iCandidateUp][2]-bottomCenters[iCandidateDown][2]>-backTrackingLimit:
if angleMax is None:
# blindStitching
# check lateralDist
lateralDist=np.sqrt(
(bottomCenters[iCandidateDown][0]-self.topCenters[iCandidateUp][0])**2+\
(bottomCenters[iCandidateDown][1]-self.topCenters[iCandidateUp][1])**2)
if lateralDist<distLateral:
successfulMatch=True
else:
#smartStitching
endPntBottom=np.array(bottomCenters[iCandidateDown][:3])
startPntTop=np.array(self.topCenters[iCandidateUp][:3])
oriVecBottom=np.array(bottomCenters[iCandidateDown][3:])
connectVec=startPntTop-endPntBottom
normConnectVec=np.linalg.norm(connectVec)
connectVec/=normConnectVec
theta=np.arccos(np.dot(oriVecBottom,connectVec))
lateralDist=np.sin(theta)*normConnectVec
if lateralDist<distLateral:
cosAnglesOrientationVecs=np.dot(
bottomCenters[iCandidateDown][3:],
self.topCenters[iCandidateUp][3:])
if abs(cosAnglesOrientationVecs)>np.cos(angleMax):
successfulMatch=True
if successfulMatch:
#successful match
matchDistance=d_up[iCandidateUp ][np.where(id_up[iCandidateUp ]==iCandidateDown)][0]
if lengths==None: #blindStitching
dataTuple=(matchDistance,lateralDist)
else:
dataTuple=(matchDistance,lateralDist,lengths[iCandidateUp],cosAnglesOrientationVecs)
keepNewMatch=True
if iCandidateDown in matches.keys():
# if match already exist for this candidateDown, keep the match which has better ranking
keepNewMatch=stitchingRanking(matches[iCandidateDown][1],dataTuple )
previousMatchUp=matches[iCandidateDown][0]
if keepNewMatch:
# if match already exist for this candidateUp, keep the match which has better ranking
if iCandidateUp in matches["listCentersTop"].keys():
previousMatchDown=matches["listCentersTop"][iCandidateUp]
keepNewMatch=stitchingRanking(matches[previousMatchDown][1],dataTuple)
if keepNewMatch:
# remove BOTH previous matches
if previousMatchDown in matchesBackup.keys():
matchesBackup[previousMatchDown].append(matches.pop(previousMatchDown))
else:
matchesBackup[previousMatchDown]=[matches.pop(previousMatchDown)]
matchesBackup["listCentersTop"][iCandidateUp] =matches["listCentersTop"].pop(iCandidateUp) #remove previous iCandidateDown
matchesBackup["listCentersTop"][previousMatchUp]=matches["listCentersTop"].pop(previousMatchUp)#remove previous iCandidateUp
else:
#remove previous match
if iCandidateDown in matchesBackup.keys():
matchesBackup[iCandidateDown].append(matches[iCandidateDown])
else:
matchesBackup[iCandidateDown]=[matches[iCandidateDown]]
# matchesBackup[iCandidateDown]=matches[iCandidateDown]
matchesBackup["listCentersTop"][previousMatchUp]=matches["listCentersTop"].pop(previousMatchUp)
else:
# if match already exist for this candidateUp, keep the match which has minimal distance
if iCandidateUp in matches["listCentersTop"].keys():
previousMatch=matches["listCentersTop"][iCandidateUp]
keepNewMatch=stitchingRanking(matches[previousMatch][1],dataTuple)
if keepNewMatch:
#remove previous match
if previousMatch in matchesBackup.keys():
matchesBackup[previousMatch].append(matches.pop(previousMatch))
else:
matchesBackup[previousMatch]=[matches.pop(previousMatch)]
# matchesBackup[previousMatch] =matches.pop(previousMatch)
matchesBackup["listCentersTop"][iCandidateUp] =matches["listCentersTop"].pop(iCandidateUp) #remove previous iCandidateDown
#edge case where both pairs of start and endpoints are a positive match (probably due to backtracking)
if iCandidateUp in matches.keys():
keepNewMatch=stitchingRanking(matches[iCandidateUp][1],dataTuple )
previousMatchDown=matches[iCandidateUp][0]
if keepNewMatch:
previousMatchUp=iCandidateUp
if iCandidateUp in matches["listCentersTop"].keys():
# if reverse match already exist for this candidateUp, check against that one
# if ranks higher, this reverse match will be poped and replaced
previousMatchUp=matches["listCentersTop"][iCandidateUp]
previousMatchDown=matches[previousMatchUp][0]
keepNewMatch=stitchingRanking(matches[previousMatchUp][1],dataTuple )
if keepNewMatch:
#remove previous match
if previousMatchUp in matchesBackup.keys():
matchesBackup[previousMatchUp].append(matches.pop(previousMatchUp))
else:
matchesBackup[previousMatchUp]=[matches.pop(previousMatchUp)]
matchesBackup["listCentersTop"][previousMatchDown]=matches["listCentersTop"].pop(previousMatchDown) #remove previous iCandidateDown
if keepNewMatch:
matches[iCandidateDown]=(iCandidateUp,dataTuple)
matches["listCentersTop"][iCandidateUp]=iCandidateDown
potentialMatches=list(matchesBackup.keys())
potentialMatches.remove("listCentersTop")
#matchesBackup are usefull in the following scenario:
# first A matched to B
# then C matched to B (better ranking)
# then C matched to D
# in matches, only C to D is kept.
# but perhaps A and B could still be a good match,
# if either wasn't matched to anything
# this possibility is checked here
for iCandidateDown in potentialMatches:
while matchesBackup[iCandidateDown]:
iCandidateUp=matchesBackup[iCandidateDown][-1][0]
if iCandidateUp in matches["listCentersTop"]:
matchesBackup[iCandidateDown].pop()
else:
matches[iCandidateDown]=matchesBackup[iCandidateDown][-1]
matches["listCentersTop"][iCandidateUp]=iCandidateDown
matchesBackup[iCandidateDown]=[]
id_bottom_th=[]
id_top_th=[]
for iDown in matches.keys():
if iDown != "listCentersTop":
id_bottom_th.append(iDown)
id_top_th.append(matches[iDown][0])
# bottomCenters[id_bottom_th] are closest to topCenters[id_top_th], within max dist
return id_bottom_th,id_top_th,matches
# keep matches that are bidirectional
id_top = np.unique(id_up[id_down])
id_bottom = id_down[id_top]
# keep matches that are closer than a distance
# idMatch = find(d_down[id_top] < dist);
idMatch = [index for index,val in enumerate(d_down[id_top]) if val<distTotal]
id_bottom_th = id_top[idMatch]
id_top_th = id_bottom[idMatch]
#test to see if more than one match in top
l_top=list(id_top_th)
repetitions=[(index,val,d_down[id_bottom_th[index]]) for index,val in enumerate(id_top_th) if l_top.count(val)>1]
repetitionsDict={}
rejectPositions=[]
# if repetitions exist, keep the one at shortest distance, and store indices of rejected ones
if len(repetitions)>0:
for index,val,dist in repetitions:
if val in repetitionsDict.keys():
if dist<repetitionsDict[val][1]:
rejectPositions.append(repetitionsDict[val][0])
repetitionsDict[val]=(index,dist)
else:
rejectPositions.append(index)
else:
repetitionsDict[val]=(index,dist)
return id_bottom_th,id_top_th,repetitionsDict,rejectPositions
def knn(topCenters,bottomCenters,dist,returnDist=False):
# build kd-tree
tree_down=KDTree(topCenters)
# search the kd-tree
# id_down: topCenter[id_down[i]] is closest to bottomCenters[i], with distance d_down[i]
[d_down, id_down] = tree_down.query(bottomCenters)
# build kd-tree
tree_up = KDTree(bottomCenters)
# search the kd-tree
# id_up: bottomCenter[id_up[i]] is closest to topCenters[i], with distance d_up[i]
[d_up, id_up] = tree_up.query(topCenters)
# keep matches that are bidirectional
id_bottom = np.unique(id_up[id_down])
id_top = id_down[np.unique(id_up[id_down])]
# keep matches that are closer than a distance
# idMatch = find(d_down[id_top] < dist);
idMatch = [index for index,val in enumerate(d_down[id_bottom]) if val<dist]
id_bottom_th = id_bottom[idMatch]
id_top_th = id_top[idMatch]
if returnDist:
dist=d_down[id_bottom[idMatch]]
# bottomCenters[id_bottom_th] are closest to topCenters[id_top_th], within max dist
return id_bottom_th,id_top_th,dist
else:
return id_bottom_th,id_top_th
def firstPassKNN(nextCt,thisCt,distLateral_knn):
# the query points are the current slice (thisCT)
# mapped into the next slice
# thisCT(id_bottom_th)==nextCT(id_top_th)
if len(nextCt)>0 and len(thisCt)>0: #no need to find neighbours if either is empty
id_bottom,id_top = knn(nextCt,thisCt,distLateral_knn)
else:
id_bottom=[]
id_top=[]
return id_bottom,id_top
def greyUint16_to_RGB(imageUint16):
imageRGB=np.zeros((imageUint16.shape[0],imageUint16.shape[1],3))
for ix in range(imageUint16.shape[0]):
for iy in range(imageUint16.shape[1]):
imageRGB[ix,iy,0]=imageUint16[ix,iy]/2**16
imageRGB[ix,iy,1]=imageUint16[ix,iy]/2**16
imageRGB[ix,iy,2]=imageUint16[ix,iy]/2**16
return imageRGB
def RBGUint8_to_Bool(imageUint8):
imageRGB=np.zeros((imageUint8.shape[0],imageUint8.shape[1]))
for ix in range(imageUint8.shape[0]):
for iy in range(imageUint8.shape[1]):
imageRGB[ix,iy,0]=imageUint8[ix,iy]/2**8
imageRGB[ix,iy,1]=imageUint8[ix,iy]/2**8
imageRGB[ix,iy,2]=imageUint8[ix,iy]/2**8
return imageRGB
def drawEllipsoid(engine,phi,theta,beta,translationVec,length,radius,representation="surface" ):
#making imports inside function so codebase works even if mayavi is unworkable on some machines
from mayavi.sources.api import ParametricSurface
from mayavi.sources.builtin_surface import BuiltinSurface
from mayavi.modules.api import Surface
from mayavi.filters.transform_data import TransformData
# Add a cylinder builtin source
ellipsoid_src = BuiltinSurface()
engine.add_source(ellipsoid_src)
ellipsoid_src.source = 'superquadric'
ellipsoid_src.data_source.center = np.array([0.,0.,0.])
ellipsoid_src.data_source.scale = ([radius,length,radius])
ellipsoid_src.data_source.phi_resolution=64
ellipsoid_src.data_source.theta_resolution=64
# Add transformation filter to translate and then rotate ellipsoid about an axis
transform_data_filter = TransformData()
engine.add_filter(transform_data_filter, ellipsoid_src)
Rt = np.eye(4)
# in homogeneous coordinates:
#rotation matrix
Rt[0:3,0:3] =vs.eul2rot( [phi,theta, beta],'zyz', unit='deg')
#translation
Rt[0:3,3]=translationVec
Rtl = list(Rt.flatten()) # transform the rotation matrix into a list
transform_data_filter.transform.matrix.__setstate__({'elements': Rtl})
transform_data_filter.widget.set_transform(transform_data_filter.transform)
transform_data_filter.filter.update()
transform_data_filter.widget.enabled = False # disable the rotation control further.
# Add surface module to the cylinder source
ellip_surface = Surface()
engine.add_filter(ellip_surface,transform_data_filter)
# add color property
ellip_surface.actor.property.color = (0.0, 0.4, 0.9)
ellip_surface.actor.property.representation = representation
def drawEllipsoidParametric(engine,phi,theta,beta,translationVec,
half_length,radius,color,representation="wireframe",opacity=0.1 ):
#making imports inside function so codebase works even if mayavi is unworkable on some machines
from mayavi.sources.api import ParametricSurface
from mayavi.sources.builtin_surface import BuiltinSurface
from mayavi.modules.api import Surface
from mayavi.filters.transform_data import TransformData
# Add a parametric surface source
ellipsoid_src = ParametricSurface()
ellipsoid_src.function = 'ellipsoid'
engine.add_source(ellipsoid_src)
# Add transformation filter to scale, translate and then rotate ellipsoid about an axis
transform_data_filter = TransformData()
engine.add_filter(transform_data_filter, ellipsoid_src)
Rt = np.eye(4)
# in homogeneous coordinates:
# scaling
scalingMat=np.eye(3)
scalingMat[0,0]*=radius
scalingMat[1,1]*=radius
scalingMat[2,2]*=half_length
# rotation matrix afterwards
Rt[0:3,0:3] =np.dot(vs.eul2rot( [phi,theta, beta],'zyz', unit='deg'),scalingMat)
# translation
Rt[0:3,3]=translationVec
Rtl = list(Rt.flatten()) # transform the rotation matrix into a list
# add transformation matrix to transform filter
transform_data_filter.transform.matrix.__setstate__({'elements': Rtl})
transform_data_filter.widget.set_transform(transform_data_filter.transform)
transform_data_filter.filter.update()
transform_data_filter.widget.enabled = False # disable the rotation control further.
# Add surface module to the cylinder source
ellip_surface = Surface()
engine.add_filter(ellip_surface,transform_data_filter)
# add rendering properties
ellip_surface.actor.property.opacity = opacity
ellip_surface.actor.property.color = color
ellip_surface.actor.mapper.scalar_visibility = False # don't colour ellipses by their scalar indices into colour map
ellip_surface.actor.property.backface_culling = True # gets rid of weird rendering artifact when opacity is < 1
ellip_surface.actor.property.specular = 0.1
# ellip_surface.actor.enable_texture=True
ellip_surface.actor.property.representation = representation
ellip_surface.scene.disable_render = True
return ellip_surface
def getPhiThetaFromVec(vec):
#normalization
vec/=np.linalg.norm(vec)
phi=np.arctan2(vec[1],vec[0])
theta=np.arccos(np.dot([0.,0.,1.],vec ))
return np.degrees(phi),np.degrees(theta)
def plotEllipsoid(fibObj,fiberDiameter,engine,opacity=0.1,representation="wireframe" ):
try:
vec=fibObj.orientationVec
except:
fibObj.processPointCloudToFiberObj(minFiberLength=1.,tagAngleTooSteep=False,maxSteepnessAngle=None)
vec=fibObj.orientationVec
phi,theta=getPhiThetaFromVec(vec)
translationVec=fibObj.meanPntCloud
half_length=fibObj.totalLength/2.
radius=fiberDiameter/2.
color=fibObj.color
return drawEllipsoidParametric(engine,phi,theta,0.,translationVec,half_length,radius,color,representation, opacity )
def fiberPloting(fibObj,iFib,nFib,nFibTracked,engine,params,scale=2.):
import mayavi.mlab as mlab
print("Drawing fiber object #{}/{},\t ({} are \"tracked\")".format(iFib,nFib,nFibTracked))
drawJaggedLines =params["drawJaggedLines"]
drawCenterLines =params["drawCenterLines"]
drawEllipsoids =params["drawEllipsoids"]
addText =params["addText"]
fiberDiameter =params["fiberDiameter"]
tube_radius=0.4
if drawJaggedLines:
if fibObj.addedTo:
tube_radius=0.5
mlab.plot3d(fibObj.x,fibObj.y,fibObj.z,
tube_radius=tube_radius,color=fibObj.color)
if drawCenterLines:
pointArray=np.concatenate((np.array(fibObj.startPnt)[:,np.newaxis],
np.array(fibObj.endPnt)[:,np.newaxis]), axis=1)
mlab.plot3d(*pointArray,
tube_radius=tube_radius,color=fibObj.color)
if drawEllipsoids:
fibObj.wireObj=plotEllipsoid(fibObj,fiberDiameter,engine,opacity=0.1,representation='wireframe')
fibObj.surfaceObj=plotEllipsoid(fibObj,fiberDiameter,engine,opacity=0.3,representation='surface')
if addText:
strText="{}".format(fibObj.fiberID)
if "zOffset" in fibObj.__dir__():
if fibObj.zOffset:
zOffset=16
else:
zOffset=10
mlab.text3d(fibObj.x[-1],fibObj.y[-1],fibObj.z[-1]+zOffset,
strText,color=fibObj.color,scale=scale)
def permute3(list3,permuteVec):
return[list3[i] for i in permuteVec]
def makeNegative(im):
im[im==255]=1
im[im==0]=255
im[im==1]=0
# padding
def paddingOfImage(im,paddingWidth=5):
# along x direction
padding=np.zeros((paddingWidth,im.shape[1]),np.uint8)
im=np.concatenate((padding,im, padding),axis=0)
# along y direction
padding=np.zeros((im.shape[0],paddingWidth),np.uint8)
return np.concatenate((padding,im, padding),axis=1)
def paddingOfImage_RGBA(im,paddingWidth=5):
# along x direction
padding=np.zeros((paddingWidth,im.shape[1],4),np.uint8)
im=np.concatenate((padding,im, padding),axis=0)
# along y direction
padding=np.zeros((im.shape[0],paddingWidth,4),np.uint8)
return np.concatenate((padding,im, padding),axis=1)
def removePaddingOfImage(im,paddingWidth=5):
return im[paddingWidth:-paddingWidth,paddingWidth:-paddingWidth]
from matplotlib.patches import Rectangle
from matplotlib.legend_handler import HandlerBase
class HandlerColormap(HandlerBase):
# allows use of colorbar as a patch in legend,
# taken from https://stackoverflow.com/questions/55501860/how-to-put-multiple-colormap-patches-in-a-matplotlib-legend
def __init__(self, cmap, num_stripes=8, **kw):
HandlerBase.__init__(self, **kw)
self.cmap = cmap
self.num_stripes = num_stripes
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize, trans):
stripes = []
for i in range(self.num_stripes):
s = Rectangle([xdescent + i * width / self.num_stripes, ydescent],
width / self.num_stripes,
height,
fc=self.cmap((2 * i + 1) / (2 * self.num_stripes)),
transform=trans)
stripes.append(s)
return stripes
# find most frequent element in a list
def most_frequent(List):
return max(set(List), key = List.count)
def blobDetection(grayImg,imSlice,convexityDefectDist,plotConvexityDefects=False,useNegative=True):
# Detect blobs by way of convexity defect
if useNegative:# required for threshold on V_fibers, not on binary mask from voxelMap
makeNegative(grayImg)
ret, thresh = cv.threshold(grayImg, 127, 255,0)
contours,hierarchy = cv.findContours(thresh,2,1)
if plotConvexityDefects:
if useNegative==False:
#use negative only for plot, not convexity testing
makeNegative(thresh)
img=cv.cvtColor(thresh,cv.COLOR_GRAY2BGR)
centroids=[]
for iCnt,cnt in enumerate(contours):
hull = cv.convexHull(cnt,returnPoints = False)
if plotConvexityDefects:
cv.drawContours(img, [cnt], 0, (165,0,255), 1)
try:
defects = cv.convexityDefects(cnt,hull)
except cv.error as e:
if e.err!='The convex hull indices are not monotonous, which can be in the case when the input contour contains self-intersections':
raise RuntimeError("unhandled exception in convexityDefects")
# The convex hull indices are not monotonous,
# which can be in the case when the input contour contains self-intersections in function 'convexityDefects'
hullLst=list(hull)
hullLst.sort(key=lambda x:x[0],reverse=True)
hull=np.array(hullLst)
defects = cv.convexityDefects(cnt,hull)
# to avoid flagging the same contour more than once
flagged=False
if defects is not None:
for i in range(defects.shape[0]):
if flagged:
continue
s,e,f,d = defects[i,0]
if d/256.0>convexityDefectDist:
flagged=True
start = tuple(cnt[s][0])
end = tuple(cnt[e][0])
far = tuple(cnt[f][0])
#find centroid of contour
m=cv.moments(cnt)
if m["m00"]>0.: # avoids colapsed contours with no area
x=m["m10"]/m["m00"]
y=m["m01"]/m["m00"]
# construct centroid object
centroids.append(centroidObj(y,x,cnt))
# x and y are flipped to conform to standard in the rest of the project, where voxelMap[x,y].
# imshow() transposes the image, so text() must be added as text(y,x) elsewhere but here
if plotConvexityDefects:
print("distance: {: >8.3f}\t contour: {}\t Defect_index: {} ##################### FLAGGED".format(d/256.0,iCnt,i))
cv.line(img,start,end,[0,255,0],1)
cv.circle(img,(int(x),int(y)),20,[0,0,255],1)
cv.putText(img, text="{}".format(iCnt), org=(far[0]+10,far[1]-10),# to the right and above
fontFace= cv.FONT_HERSHEY_SIMPLEX, fontScale=0.5, color=(220,10,40),
thickness=2, lineType=cv.LINE_AA)
if plotConvexityDefects:
from matplotlib import pyplot as plt
plt.figure(figsize=[8,8])
plt.imshow(img)
plt.title("convexity defect detection result, imSlice={}".format(imSlice),fontsize=22)
plt.tight_layout()
plt.show()
return centroids
def addPatchToLegend(legend,color,label):
ax = legend.axes
handles, labels = ax.get_legend_handles_labels()
handles.append(mpatches.Patch(facecolor=color, edgecolor=color))
labels.append(label)
legend._legend_box = None
legend._init_legend_box(handles, labels)
legend._set_loc(legend._loc)
legend.set_title(legend.get_title().get_text())
def makeBinaryMap(voxelMap):
binaryVoxelMap=np.array(voxelMap,np.int16)
maxVal=np.iinfo(binaryVoxelMap.dtype).max # ==32767 for signed int16 (wont be a problem unless fiber number exceeds in this slice, which can't be contained in voxelMap anyway)
binaryVoxelMap[binaryVoxelMap>2]= maxVal # marker values for individual connected regions
binaryVoxelMap[binaryVoxelMap<=2]=0 # value for background and outlines
binaryVoxelMap[binaryVoxelMap==maxVal]=255 # remap for np.uint8
return np.array(binaryVoxelMap,np.uint8)
def watershedTransform(imageSliceGray,
imageHist,
imSlice,
initialWaterLevel,
waterLevelIncrements,
convexityDefectDist,
checkConvexityAndSplit =True,
plotInitialAndResults =False,
plotEveryIteration =False,
plotWatershedStepsGlobal =False,
plotWatershedStepsMarkersOnly =False,
openingBeforeWaterRising =False,
plotConvexityDefects =False,
paddingWidth =5,
doNotPltShow =False,
figsize =[8,8],
legendFontSize =32,
titleFontSize =22,
textFontSize =26
):
# if initialWaterLevel is kept below 1.0 small regions are not erased, but produces many spurious detections
# cv.watershed is used only to obtain initial labelling (markers) of connected regions.
voxelMap_slice, grayImg, img3channel, paddingWidth,seeds,dist_transform=findWatershedMarkers(
imageSliceGray,
initialWaterLevel,
imSlice=imSlice,
plotEveryStep=plotWatershedStepsGlobal
)
binaryVoxelMap=makeBinaryMap(voxelMap_slice)
if checkConvexityAndSplit:
#detect blobs that have convexity defects, which need to be split by rising waterLevel (for some datasets this is unneccessary)
centroids = blobDetection(binaryVoxelMap,imSlice,convexityDefectDist,plotConvexityDefects,useNegative=False)
else:
centroids=[]
seeds=voxelMap_slice
seeds[1,1]=seeds[0,0] # remove hack at (1,1)
markerList_notConvex=[]
for iC,centroid in enumerate(centroids):
markerList_notConvex.append(centroid.getMarker(seeds,exclusionList=[-1,2]) )
markerList_notConvex.sort()
if plotInitialAndResults:
plt.rcParams.update({'font.size': 26})
plt.rcParams['axes.facecolor'] = 'white'
plt.rcParams["font.family"] = "Times New Roman"
cmapStr_voxelMap="Blues"
singleColor_convex=(0.2,0.5,0.7,1.) #use None for color gradient instead
cmapStr_voxelMap_reProcessed='Wistia'#'YlGn'#'plasma'
numColors_reProcessed=5
cmap_rejected=cm.get_cmap('autumn') #Reds
singleColor_rejected=(0.68,0.11,0.,1.)
fig=plt.figure(figsize=figsize,num="rejectedSeedsConvexityTest_imSlice{}".format(imSlice))
imageHist=paddingOfImage(imageHist,paddingWidth)
voxelImg=overlayVoxelMapToHist_composite(
voxelMap_slice [paddingWidth:-paddingWidth,paddingWidth:-paddingWidth],
imageHist[paddingWidth:-paddingWidth,paddingWidth:-paddingWidth],
exclusionList=[2,0,-1],
cmapStr=cmapStr_voxelMap,
singleColor=singleColor_convex
)
plt.imshow(voxelImg)
temp=paddingOfImage_RGBA(voxelImg)
for i,centroid in enumerate(centroids):
temp=centroid.addFilledContourToImg(temp,color=(1.,0.,0.,1.))
imgExtracted=temp[paddingWidth:-paddingWidth,paddingWidth:-paddingWidth,:]
plt.title("result convexity test, imSlice={}".format(imSlice), fontsize=titleFontSize)
uniqueLabel=True
for iC,centroid in enumerate(centroids):
#x and y are transposed in imshow() convention
pnt=centroid.getPnt()
marker=centroid.getMarker()
if uniqueLabel:#single legend entry
plt.scatter(pnt[1]-paddingWidth, pnt[0]-paddingWidth, s=100,c="red",label="Rejected Blobs (##_##=> markerNum_contourNum)")
plt.text (pnt[1]+5-paddingWidth,pnt[0]+5-paddingWidth,s="{}_{}".format(marker,iC),c="red",fontsize=textFontSize)
uniqueLabel=False
else:
plt.scatter(pnt[1]-paddingWidth, pnt[0]-paddingWidth, s=100,c="red")
plt.text (pnt[1]+5-paddingWidth,pnt[0]+5-paddingWidth,s="{}_{}".format(marker,iC),c="red",fontsize=textFontSize)
plt.legend(fontsize=legendFontSize,framealpha=1.)
fig.tight_layout(pad=0.05)
fig=plt.figure(figsize=figsize,num="resultConvexityTest_imSlice{}".format(imSlice))
plt.imshow(imgExtracted)
plt.title("result Convexity Test imSlice={}".format(imSlice), fontsize=titleFontSize)
fig.tight_layout(pad=0.05)
cmaps = [plt.cm.get_cmap(cmapStr_voxelMap), cmap_rejected]
cmap_labels = [ "Single fiber blobs","Rejected blobs"]
if singleColor_convex is None:
# create proxy artists as handles:
cmap_handles = [Rectangle((0, 0), 1, 1) for _ in cmaps]
handler_map = dict(zip(cmap_handles,
[HandlerColormap(cm, num_stripes=32) for cm in cmaps]))
# cmap_handles[1].set_color(singleColor_rejected)
# del handler_map[cmap_handles[1]]
plt.legend(handles=cmap_handles,
labels=cmap_labels,
handler_map=handler_map,
fontsize=legendFontSize,framealpha=1.)
else:
# create a patch (proxy artist) for every color
colors=[singleColor_convex,singleColor_rejected]
patches = [ mpatches.Patch(color=colors[i], label="{l}".format(l=cmap_labels[i]) ) for i in range(len(cmap_labels)) ]
# put those patched as legend-handles into the legend
plt.legend(handles=patches,fontsize=legendFontSize,framealpha=1.)
for markerVal in markerList_notConvex:
if plotEveryIteration:
print("markerVal",markerVal)
#starting point for seeds for this marker
binaryMapThisMarker=np.zeros(seeds.shape)
binaryMapThisMarker[seeds==markerVal]=1 #markerVal True value
seedsThisMarker = findWatershedMarkers(
binaryMapThisMarker,
initialWaterLevel,
imSlice=imSlice,
paddingWidth=0,
plotEveryStep=plotWatershedStepsMarkersOnly,
fromThresh=True # use binary map from threshold of input instead of eroded sure_fg (foreground)
# as input to find connected regions. So that small regions are not erased
)[4]
numBefore=len(np.unique(seedsThisMarker))
if openingBeforeWaterRising:
# the effect is negligible. sometimes splits region in two,
# but where raising level would probably do it as well
seedsThisMarker=np.array(seedsThisMarker,np.uint8) #morphologyEx cant use int32
cnts = cv.findContours(seedsThisMarker, cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)[-2]
numBefore= len(cnts)
kernel = np.ones((4, 4), np.uint8)
seedsThisMarkerTrial = cv.morphologyEx(seedsThisMarker, cv.MORPH_OPEN, kernel)
cnts = cv.findContours(seedsThisMarkerTrial, cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)[-2]
numAfter= len(cnts)
if numAfter>numBefore: # if blob was split by opening
# this prevents the use of opening if the number of blobs is unchanged
seedsThisMarker=seedsThisMarkerTrial
if plotEveryIteration:
fig=plt.figure(figsize=figsize,num="initial_seeds_map_UNIQUE_marker{}_imSlice{}".format(markerVal,imSlice))
plt.imshow(seedsThisMarker,cmap="binary")
plt.title("initial seeds map UNIQUE marker={}, imSlice={}".format(markerVal,imSlice), fontsize=titleFontSize)
fig.tight_layout(pad=0.05)
print("numBefore",numBefore)
keepRising=True
if waterLevelIncrements<0: #don't do iterative water raising
keepRising=False
risingCounter=0 #to avoid getting stuck in while loop
waterLevel=initialWaterLevel
while keepRising and risingCounter<12:
risingCounter+=1
waterLevel+=waterLevelIncrements
seedsHighWater = findWatershedMarkers(seedsThisMarker,waterLevel,paddingWidth=0)[4] # get new connectedMap
seedsHighWater[1,1]=seedsHighWater[0,0] # remove hack at (1,1)
numAfter=len(np.unique(seedsHighWater))
if plotEveryIteration:
fig=plt.figure(figsize=figsize,num="waterLevel_raised_seedsMap_marker{}_imSlice{}".format(markerVal,imSlice))
plt.imshow(seedsHighWater)
plt.title("waterLevel raised seeds map, marker={}, imSlice={}".format(markerVal,imSlice), fontsize=titleFontSize)
plt.tight_layout()
if ~doNotPltShow:
plt.show()
print("numAfter",numAfter)
if numAfter<numBefore or numAfter==1:
keepRising=False
else: # number of connected regions has increased or remained at n>1
if numAfter>numBefore:
#check if a new connected region had convexity defects,if True split it to another while loop
newMarkerList=list(np.unique(seedsHighWater))
newMarkerList.remove(0) # background value
# if there isn't more than one connected region after new waterLevel, no need to check for
# convexity defect: the only region present will already go through more cycles
if len(newMarkerList)>1:
seeds[seeds==markerVal]=0