forked from chrisadamsonmcri/CCSegThickness
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CCSegPipeSeg.py
executable file
·2405 lines (1988 loc) · 99.9 KB
/
CCSegPipeSeg.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
#!/usr/bin/python
import tempfile
import os
import scipy
import cv2
import math
import numpy
import nibabel
import pylab
import h5py
import shutil
import CCSegUtils
import Otsu
import skimage.morphology
import skimage.feature
import skimage.color
# My Lucas-Kanade tracker
import LKTracker
from matplotlib.font_manager import FontProperties
import errno
import scipy.ndimage
from joblib import Parallel, delayed
def watershedTransformSeg(IMG, Seg, penaltyIMG = None):
watershedMask = scipy.ndimage.morphology.binary_dilation(Seg, structure = radialStrel(7))
segEroded = scipy.ndimage.morphology.binary_erosion(Seg, structure = numpy.ones((3, 3)))
#segEroded = numpy.array(Seg)
watershedMaskEroded = scipy.ndimage.morphology.binary_erosion(watershedMask, structure = numpy.ones((3, 3)))
outerMarker = numpy.logical_and(numpy.logical_not(watershedMaskEroded), watershedMask)
if penaltyIMG is None:
gaussianDerivFilter = numpy.atleast_2d(numpy.array([0.0021, 0.4319, 0, -0.4319, -0.0021]))
#print gaussianDerivFilter
#print gaussianDerivFilter.T
FX = scipy.ndimage.filters.convolve(IMG, gaussianDerivFilter, mode = 'nearest')
FY = scipy.ndimage.filters.convolve(IMG, gaussianDerivFilter.T, mode = 'nearest')
edgeMAG = numpy.sqrt(FX * FX + FY * FY)
edgeMAG[numpy.logical_not(watershedMask)] = 0
penaltyIMG = numpy.array(edgeMAG)
#peak_local_max(-edgeMAG, indices = False, footprint = numpy.ones((3, 3)), labels=image)
#SE = numpy.ones((3, 3))
#T = scipy.ndimage.morphology.grey_erosion(edgeMAG, footprint = SE)
#localMin = numpy.logical_and(T == edgeMAG, edgeMAG > 0)
#watershedMarkers = numpy.logical_or(localMin, Seg)
watershedMarkers = numpy.logical_or(segEroded, outerMarker)
watershedMarkers = scipy.ndimage.measurements.label(numpy.uint16(watershedMarkers), structure = numpy.ones([3, 3]))[0]
#
# print watershedMarkers[segEroded]
# pylab.clf()
# pylab.subplot(2, 2, 1)
# CCSegUtils.showIMG(watershedMarkers)
# pylab.subplot(2, 2, 2)
# CCSegUtils.showIMG(outerMarker)
# pylab.subplot(2, 2, 3)
# CCSegUtils.showIMG(segEroded)
#
# pylab.gcf().set_size_inches((20, 10), forward = True)
# pylab.show()
#
watershedSegLabels = numpy.unique(watershedMarkers[segEroded])
#print I
#I = watershedMarkers[segEroded]
#print watershedSegLabels
#watershedSegLabels = I[0]
watershedTransform = skimage.morphology.watershed(penaltyIMG, numpy.uint16(watershedMarkers), mask = watershedMask)
#watershedAreas = regionProps(watershedTransform, ['area'])
#I = numpy.argmax(watershedAreas['area'])
#watershedSeg = (watershedTransform == I + 1)
#watershedSeg = (watershedTransform == watershedSegLabel)
#watershedSeg, junk = CCSegUtils.ismember(watershedTransform, watershedSegLabels)
watershedSeg = numpy.in1d(numpy.ravel(watershedTransform), numpy.ravel(watershedSegLabels))
#print watershedSeg
#print watershedSegLabels
watershedSeg = numpy.reshape(watershedSeg, watershedTransform.shape)
#print watershedSeg.shape
return (watershedSeg, watershedMarkers, watershedTransform, penaltyIMG)
# implements imfill(BW, 'holes')
def bwFillHoles(BW):
assert(isinstance(BW, numpy.ndarray) and BW.dtype == numpy.bool)
mask = numpy.pad(numpy.logical_not(BW), 1, mode='constant', constant_values = 1)
marker = numpy.pad(numpy.zeros(BW.shape, dtype=numpy.bool), 1, mode='constant', constant_values = 1)
numDilations = 0
while True:
oldMarker = numpy.array(marker)
marker = numpy.logical_and(mask, scipy.ndimage.morphology.binary_dilation(marker, structure = numpy.ones((3, 3), dtype=numpy.bool)))
if numpy.array_equal(oldMarker, marker):
break;
numDilations = numDilations + 1
del oldMarker
print "bwFillHoles finished with " + str(numDilations) + " dilations"
marker = numpy.take(marker, numpy.arange(1, marker.shape[0] - 1), axis = 0)
marker = numpy.take(marker, numpy.arange(1, marker.shape[1] - 1), axis = 1)
#pylab.subplot(1, 2, 1); CCSegUtils.showIMG(marker);
#pylab.subplot(1, 2, 2); CCSegUtils.showIMG(BW);
return numpy.logical_not(marker)
#return numpy.logical_or(BW, numpy.logical_not(marker))
# bwselect using masks
# label the Mask
# extract all values in the labeled Mask under the marker
# retain only labels that overlap with the marker
def bwSelectWithMask(mask, marker):
outIMG = numpy.zeros(marker.shape, dtype = numpy.bool)
if not numpy.any(marker):
return outIMG
else:
BWLabels, numLabels = scipy.ndimage.measurements.label(mask, structure = numpy.ones([3, 3]))
labelsUnderMarker = BWLabels[marker]
labelsUnderMarker = labelsUnderMarker[labelsUnderMarker.nonzero()]
labelsUnderMarker = numpy.unique(labelsUnderMarker)
#print "labelsUnderMarker: " + str(labelsUnderMarker)
for z in range(numpy.size(labelsUnderMarker)):
outIMG = numpy.logical_or(outIMG, BWLabels == labelsUnderMarker[z])
return outIMG
def dicesCoefficient(A, B):
return 2.0 * numpy.sum(numpy.logical_and(A, B)) / (numpy.sum(A) + numpy.sum(B))
def bwAreaOpen(BW, areaThresh):
outIMG = numpy.zeros(BW.shape, dtype=numpy.bool)
BWLabels, numLabels = scipy.ndimage.measurements.label(BW, structure = numpy.ones([3, 3]))
if numLabels >= 1:
BWRegionProps = CCSegUtils.regionProps(BWLabels, ['Area'])
I = numpy.where(BWRegionProps['area'] > areaThresh)[0]
for z in range(numpy.size(I)):
outIMG = numpy.logical_or(outIMG, BWLabels == I[z] + 1)
return outIMG
def imMatchHist(inputIMG, targetIMG):
# performs histogram matching so that the intensities of InputIMG are remapped to correspond to the histogram of TargetIMG
#targetIMGBins, binSpacing = numpy.linspace(numpy.min(targetIMG), numpy.max(targetIMG), num = numBins - 2, retstep = True)
numBins = 10000
targetIMGHist, targetIMGBins = numpy.histogram(numpy.ravel(targetIMG), bins = numBins, density = False)
targetIMGHist = numpy.double(targetIMGHist)
# density doesnt normalize to 1, so do that
targetIMGHist = targetIMGHist / numpy.sum(targetIMGHist)
targetIMGHistCDF = numpy.cumsum(targetIMGHist)
# make the bins centres, not edges
targetIMGBins = targetIMGBins[:-1] + numpy.diff(targetIMGBins) / 2
#print targetIMGBins
# remove zero count bins
I = numpy.nonzero(targetIMGHist)
targetIMGBins = targetIMGBins[I]
targetIMGHistCDF = targetIMGHistCDF[I]
inputIMGHist, inputIMGBins = numpy.histogram(numpy.ravel(inputIMG), bins = numBins, density = False)
inputIMGHist = numpy.double(inputIMGHist)
inputIMGHist = inputIMGHist / numpy.sum(inputIMGHist)
inputIMGHistCDF = numpy.cumsum(inputIMGHist)
inputIMGBins = inputIMGBins[:-1] + numpy.diff(inputIMGBins) / 2
# remove zero-count bins
I = numpy.nonzero(inputIMGHist)
inputIMGBins = inputIMGBins[I]
inputIMGHistCDF = inputIMGHistCDF[I]
#pylab.subplot(1, 2, 1)
#pylab.plot(inputIMGBins, inputIMGHistCDF, 'b-', targetIMGBins, targetIMGHistCDF, 'g-')
#pylab.show()
# find the point on the CDF of the input image of each of the input pixels
CDFOfInputIMG = numpy.interp(numpy.ravel(inputIMG), inputIMGBins, inputIMGHistCDF)
# find the bins that are the same point on the CDF of the target image
matchedIMG = numpy.interp(CDFOfInputIMG, targetIMGHistCDF, targetIMGBins)
matchedIMG = numpy.reshape(matchedIMG, inputIMG.shape)
return matchedIMG
#pylab.plot(targetIMGBins[:-1] + numpy.diff(targetIMGBins) / 2, targetIMGHist)
#pylab.show()
#print targetIMGHist.shape
#print targetIMGBins.shape
#% get the CDFs of the histogram of the target image
# [TargetIMGHist, TargetIMGBins] = hist(TargetIMG(:), TargetIMGBins);
# TargetIMGHist = TargetIMGHist ./ sum(TargetIMGHist);
# TargetIMGHistCDF = cumsum(TargetIMGHist);
# % get the CDFs of the histogram of the matched filter
#
# InputIMGBins = linspace(min(InputIMG(:)), max(InputIMG(:)), NumBins - 2);
# S = InputIMGBins(2) - InputIMGBins(1);
# InputIMGBins = [InputIMGBins(1) - S, InputIMGBins, InputIMGBins(end) + S];
# clear S;
# [InputIMGHist, InputIMGBins] = hist(InputIMG(:), InputIMGBins);
# InputIMGHist = InputIMGHist ./ sum(InputIMGHist);
# InputIMGHistCDF = cumsum(InputIMGHist);
#
# % use unique to create a CDF with no repeated elements
# [UInputIMGHistCDF, I] = unique(InputIMGHistCDF);
# UInputIMGHistCDFBins = InputIMGBins(I);
#
# [UTargetIMGHistCDF, I] = unique(TargetIMGHistCDF);
# UTargetIMGHistCDFBins = TargetIMGBins(I);
# clear I J;
#
# CDFInputIMGPixels = interp1(UInputIMGHistCDFBins, UInputIMGHistCDF, InputIMG(:));
# MatchedIMG = interp1(UTargetIMGHistCDF, UTargetIMGHistCDFBins, CDFInputIMGPixels);
#
# MatchedIMG = reshape(MatchedIMG, size(InputIMG));
#function [InitialResampledAVW, ...
# MatchedFilterRemapped, ...
# LKParameters, LKCost, ...
# TX, TY, InterpX, InterpY, ...
# TemplateLKIMG, TemplateProbLKIMG, FornixProbLKIMG, ...
# ResampledGroundCropped, ResampledAVWCropped, ...
# TemplateProbLKIMGCropped, FornixProbLKIMGCropped, ...
# OriginalOtsuMask, OtsuMask, ...
# TemplateOverlap, OtsuSEG] = do_lk_and_otsu(ResampledAVW, MatchedFilter, MatchedFilterProb, MatchedFilterFornixProb, ResampledGroundAVW, real_total_offset, DoLK)
#pylab.show()
#pylab.imshow(RW, origin = 'lower')
#print numpy.array([ normXCorrCenterI, normXCorrCenterJ])
#pylab.imshow(resampledAVW, origin = 'lower')
#pylab.plot(normXCorrCenterJ, normXCorrCenterI, marker='o', markerfacecolor='blue', markersize=12)
#pylab.plot(I[1], I[0], marker='o', markerfacecolor='red', markersize=3, linestyle='none')
#pylab.plot([centreXCorrMaxJ, centreXCorrMaxJ + croppedTemplateAVW.shape[1]], [centreXCorrMaxI, centreXCorrMaxI])
#pylab.plot([centreXCorrMaxJ, centreXCorrMaxJ + croppedTemplateAVW.shape[1]], [centreXCorrMaxI + croppedTemplateAVW.shape[0], centreXCorrMaxI + croppedTemplateAVW.shape[0]])
#pylab.plot([centreXCorrMaxJ, centreXCorrMaxJ], [centreXCorrMaxI, centreXCorrMaxI + croppedTemplateAVW.shape[0]])
#pylab.plot([centreXCorrMaxJ + croppedTemplateAVW.shape[1], centreXCorrMaxJ + croppedTemplateAVW.shape[1]], [centreXCorrMaxI, centreXCorrMaxI + croppedTemplateAVW.shape[0]])
def segCCLKandOtsu(IMG, templateIMG, templateCCProbIMG, templateFornixProbIMG, groundIMG, initialTranslation, DoLK = True, targetIMGMask = None):
#print "Initial translation: " + str(initialTranslation)
#print "IMG size: " + str(IMG.shape)
#print "Template size: " + str(templateIMG.shape)
#print numpy.arange(initialTranslation[1], initialTranslation[1] + templateIMG.shape[1])
croppedIMG = numpy.take(IMG, numpy.arange(initialTranslation[0], initialTranslation[0] + templateIMG.shape[1]), axis = 1)
#print croppedIMG.shape
croppedIMG = numpy.take(croppedIMG, numpy.arange(initialTranslation[1], initialTranslation[1] + templateIMG.shape[0]), axis = 0)
remappedTemplateIMG = imMatchHist(templateIMG, croppedIMG)
#remappedTemplateIMGHist, remappedTemplateIMGBins = numpy.histogram(numpy.ravel(remappedTemplateIMG), bins = 100, density = True)
#remappedTemplateIMGBins = remappedTemplateIMGBins[:-1] + numpy.diff(remappedTemplateIMGBins)
#croppedIMGHist, croppedIMGBins = numpy.histogram(numpy.ravel(croppedIMG), bins = 100, density = True)
#croppedIMGBins = croppedIMGBins[:-1] + numpy.diff(croppedIMGBins)
#pylab.plot(croppedIMGBins, croppedIMGHist)
#pylab.plot(remappedTemplateIMGBins, remappedTemplateIMGHist)
#pylab.show()
if DoLK == True:
numLKIterations = 100
else:
numLKIterations = 0
LKParameters, LKCost = LKTracker.weightedAffineInvComp(IMG, remappedTemplateIMG, templateIMG / numpy.max(templateIMG), numpy.array([0, 0, 0, 0, initialTranslation[0], initialTranslation[1]]), numLKIterations, targetIMGMask = targetIMGMask)
# [TX, TY, InterpX, InterpY] = coords_template_lk_img(LKParameters, ResampledAVW, MatchedFilter);
# find the coordinates of the template after the warp onto the target image
TX, TY, interpX, interpY = LKTracker.coordsOfAffineWarpedTemplate(LKParameters, IMG, templateIMG)
#pylab.subplot(2, 2, 1); CCSegUtils.showIMG(TX);
#pylab.subplot(2, 2, 2); CCSegUtils.showIMG(TY);
#pylab.subplot(2, 2, 3); CCSegUtils.showIMG(InterpX);
#pylab.subplot(2, 2, 4); CCSegUtils.showIMG(InterpY);
#pylab.show()
#quit()
# resample the template in the image space
templateLKIMG = CCSegUtils.interp2q(numpy.arange(1, templateIMG.shape[1] + 1), numpy.arange(1, templateIMG.shape[0] + 1), templateIMG, interpX, interpY, extrapval = numpy.nan)
templateCCProbLKIMG = CCSegUtils.interp2q(numpy.arange(1, templateIMG.shape[1] + 1), numpy.arange(1, templateIMG.shape[0] + 1), templateCCProbIMG, interpX, interpY, extrapval = 0)
templateFornixProbLKIMG = CCSegUtils.interp2q(numpy.arange(1, templateIMG.shape[1] + 1), numpy.arange(1, templateIMG.shape[0] + 1), templateFornixProbIMG, interpX, interpY, extrapval = 0)
#pylab.subplot(2, 2, 1); CCSegUtils.showIMG(templateLKIMG);
#pylab.subplot(2, 2, 2); CCSegUtils.showIMG(templateCCProbLKIMG);
#pylab.subplot(2, 2, 3); CCSegUtils.showIMG(templateFornixProbLKIMG);
#pylab.subplot(2, 2, 4); CCSegUtils.showIMG(numpy.isnan(templateLKIMG));
#pylab.show()
#quit()
# find the valid bounding box of the template in the image space
I = numpy.where(numpy.logical_not(numpy.isnan(templateLKIMG)))
cropRows = numpy.arange(numpy.min(I[0]), numpy.max(I[0]) + 1)
cropCols = numpy.arange(numpy.min(I[1]), numpy.max(I[1]) + 1)
del I
# crop the warped images
croppedIMG = IMG.take(cropRows, axis = 0).take(cropCols, axis = 1)
croppedTemplateLKIMG = templateLKIMG.take(cropRows, axis = 0).take(cropCols, axis = 1)
croppedTemplateCCProbLKIMG = templateCCProbLKIMG.take(cropRows, axis = 0).take(cropCols, axis = 1)
croppedTemplateFornixProbLKIMG = templateFornixProbLKIMG.take(cropRows, axis = 0).take(cropCols, axis = 1)
if not groundIMG == None:
croppedGroundIMG = groundIMG.take(cropRows, axis = 0).take(cropCols, axis = 1)
else:
croppedGroundIMG = None
# reset the NaN values in the warped template to zero
croppedTemplateLKIMG[numpy.where(numpy.isnan(croppedTemplateLKIMG))] = 0
# [THRESH, OtsuSEG] = robust_otsu2(ResampledAVWCropped, [0.05, 0.98]);
# OtsuSEG(ResampledAVWCropped > THRESH(end)) = 3;
# OtsuMask = (OtsuSEG == 3);
otsuSeg = Otsu.robustOtsu(croppedIMG, [0.05, 0.98], NumberClasses=3, maskOutZeros = True)
otsuSegWM = (otsuSeg == 3)
origOtsuSegWM = numpy.array(otsuSegWM)
#pylab.subplot(1, 2, 1); CCSegUtils.showIMG(origOtsuSegWM);
#pylab.subplot(1, 2, 2); CCSegUtils.showIMG(croppedIMG);
#pylab.show()
#quit()
del otsuSeg
templateFornixMask = (croppedTemplateFornixProbLKIMG > 0.01)
# FornixMaskIdx = find((FornixProbLKIMGCropped * 50) > 0.5);
# OtsuMaskCC = bwconncomp(OtsuMask);
# OtsuMaskL = labelmatrix(OtsuMaskCC);
# OtsuMaskR = regionprops(OtsuMaskCC, 'Area', 'PixelIdxList');
otsuSegWMLabels, numLabels = scipy.ndimage.measurements.label(otsuSegWM, structure = numpy.ones([3, 3]))
otsuSegWMRegionProps = CCSegUtils.regionProps(otsuSegWMLabels, ['Area', 'Mask'])
#pylab.subplot(1, 2, 1); CCSegUtils.showIMG(otsuSegWMLabels);
#pylab.show()
#quit()
# TemplateOverlap = zeros(length(OtsuMaskR), 1);
# % keep all regions that have high overlap with template or big area
# for z = 1:length(OtsuMaskR)
# IDX = setdiff(OtsuMaskR(z).PixelIdxList, FornixMaskIdx);
# TemplateOverlap(z) = sum(TemplateProbLKIMGCropped(IDX)) ./ length(IDX);
# clear IDX;
# end
templateOverlap = numpy.zeros((numLabels))
J = numpy.argmax(otsuSegWMRegionProps['area'])
for z in range(numLabels):
M = numpy.logical_and(otsuSegWMRegionProps['mask'][z], numpy.logical_not(templateFornixMask))
# if z == J:
# #print J
# #print otsuSegWMRegionProps['area']
# SR = 1
# SC = 3
# pylab.subplot(SR, SC, 1)
# CCSegUtils.showIMG(otsuSegWMRegionProps['mask'][z])
# pylab.subplot(SR, SC, 2)
# CCSegUtils.showIMG(templateFornixMask)
# pylab.subplot(SR, SC, 3)
# CCSegUtils.showIMG(croppedTemplateCCProbLKIMG)
#
# pylab.gcf().set_size_inches((20, 10), forward = True)
# pylab.show()
# quit()
#
if numpy.any(M):
#print numpy.sum(M)
templateOverlap[z] = numpy.sum(croppedTemplateCCProbLKIMG[M]) / numpy.sum(M)
del M
#rint templateOverlap
largeTemplateOverlapIDX = numpy.where(templateOverlap > 0.01)[0]
#print otsuSegWMRegionProps['area'][largeTemplateOverlapIDX]
#print templateOverlap[largeTemplateOverlapIDX]
#quit()
#print templateOverlap
#print largeTemplateOverlapIDX
#print otsuSegWMRegionProps['area']
#print otsuSegWMRegionProps['area'][largeTemplateOverlapIDX]
otsuSegCC = numpy.zeros(otsuSegWM.shape, dtype=numpy.bool)
if numpy.size(largeTemplateOverlapIDX) > 0:
I = numpy.where(otsuSegWMRegionProps['area'][largeTemplateOverlapIDX] >= 200)[0]
if numpy.size(I) == 0:
# select the region with the highest overlap
I = numpy.argmax(templateOverlap)
otsuSegCC = numpy.array(otsuSegWMRegionProps['mask'][I])
#CCSegUtils.showIMG(otsuSegCC)
# SR = 2
# SC = 2
# pylab.subplot(SR, SC, 1)
# CCSegUtils.showIMG(otsuSegWMLabels == largeTemplateOverlapIDX[J] + 1)
#
# pylab.subplot(SR, SC, 2)
# CCSegUtils.showIMG(croppedTemplateCCProbLKIMG)
#
# for z in range(numpy.size(largeTemplateOverlapIDX)):
# otsuSegCC = numpy.logical_or(otsuSegCC, otsuSegWMLabels == largeTemplateOverlapIDX[z] + 1)
#
# pylab.subplot(SR, SC, 3)
# CCSegUtils.showIMG(otsuSegCC)
#
# pylab.subplot(SR, SC, 4)
#
# I = numpy.argmax(otsuSegWMRegionProps['area'])
#
# CCSegUtils.showIMG(otsuSegWMLabels == I + 1)
#
#pylab.gcf().set_size_inches((20, 10), forward = True)
#pylab.show()
#quit()
else:
#print I
for z in range(numpy.size(I)):
otsuSegCC = numpy.logical_or(otsuSegCC, otsuSegWMRegionProps['mask'][largeTemplateOverlapIDX[I[z]]])#otsuSegWMLabels == largeTemplateOverlapIDX[I[z]] + 1)
return (TX, TY, interpX, interpY, croppedIMG, croppedTemplateLKIMG, croppedTemplateCCProbLKIMG, croppedTemplateFornixProbLKIMG, croppedGroundIMG, otsuSegCC, cropRows, cropCols, LKCost)
#pylab.subplot(2, 2, 1); CCSegUtils.showIMG(croppedTemplateLKIMG);
#pylab.subplot(2, 2, 2); CCSegUtils.showIMG(croppedTemplateCCProbLKIMG);
#pylab.subplot(2, 2, 3); CCSegUtils.showIMG(croppedTemplateFornixProbLKIMG);
#pylab.subplot(2, 2, 4); CCSegUtils.showIMG(otsuSegCC);
#pylab.show()
#quit()
# I = find(TemplateOverlap > 0.01);
# if(~isempty(I))
# OtsuMask = ismember(OtsuMaskL, I);
# OtsuMask = bwareaopen(OtsuMask, 200);
# clear Junk OtsuMaskL OtsuMaskR I;
# else
# disp('Current XCORR and LK failed');
# OtsuMask = false(size(OtsuMaskL));
# end
def nearestAnglesDistances(templateSegMask, estSegMask):
if numpy.all(templateSegMask == False) or numpy.all(estSegMask == False):
return (None, None)
templateSegContours, hierarchy = cv2.findContours(numpy.uint8(templateSegMask), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
#assert(len(templateSegContours) == 1),"Template CC seg has multiple contours, this should never happen"
if(not (len(templateSegContours) == 1)):
return (None, None)
smoothingFilter = numpy.array([1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0])
smoothingFilter = numpy.atleast_2d(smoothingFilter)
tangentFilter = numpy.array([1, 0, -1])
tangentFilter = numpy.atleast_2d(tangentFilter)
templateSegContour = numpy.squeeze(templateSegContours[0]).T
#print smoothingFilter.shape
#print templateSegContour.shape
smoothedTemplateSegContour = scipy.ndimage.filters.convolve(numpy.double(templateSegContour), smoothingFilter, mode = 'wrap')
tangentTemplateSegContour = scipy.ndimage.filters.convolve(numpy.double(smoothedTemplateSegContour), tangentFilter, mode = 'wrap')
# normalise the tangents to unit magnitude, numpy does the broadcasting for us so we just need to divide by the magnitudes
#print tangentTemplateSegContour
#print numpy.sqrt(numpy.sum(tangentTemplateSegContour * tangentTemplateSegContour, axis = 0))
T = numpy.sqrt(numpy.sum(tangentTemplateSegContour * tangentTemplateSegContour, axis = 0))
T[numpy.where(T == 0)] = 1
tangentTemplateSegContour = tangentTemplateSegContour / T
del T
#print templateSegContour[0]
#print smoothedTemplateSegContour[0]
#print smoothedTemplateSegContour[0].shape
#print numpy.concatenate([smoothedTemplateSegContour[0], numpy.array([smoothedTemplateSegContour[0, 0]])])
#print smoothedTemplateSegContour.shape
#CCSegUtils.showIMG(templateSegMask); CCSegUtils.plotContour(smoothedTemplateSegContour);
#pylab.gcf().set_size_inches((20, 10), forward = True)
#pylab.show()
#quit()
estSegContoursFirst, hierarchy = cv2.findContours(numpy.uint8(estSegMask), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
del hierarchy
estSegContours = list()
for z in range(len(estSegContoursFirst)):
estSegContours.append(numpy.atleast_2d(numpy.squeeze(estSegContoursFirst[z]).T))
del estSegContoursFirst
smoothedEstSegContours = list()
tangentEstSegContours = list()
#CCSegUtils.showIMG(allSegMasks)
#CCSegUtils.plotContour(smoothedTemplateSegContour)
for z in range(len(estSegContours)):
if estSegContours[z].shape[0] == 2:
smoothedEstSegContours.append(scipy.ndimage.filters.convolve(numpy.double(estSegContours[z]), smoothingFilter, mode = 'wrap'))
tangentEstSegContours.append(scipy.ndimage.filters.convolve(numpy.double(smoothedEstSegContours[-1]), tangentFilter, mode = 'wrap'))
#print smoothedEstSegContours[z].shape
#CCSegUtils.plotContour(smoothedEstSegContours[z])
#pylab.gcf().set_size_inches((20, 10), forward = True)
#pylab.show()
#quit()
allSmoothedEstSegContours = numpy.concatenate(smoothedEstSegContours, axis = 1)
allTangentEstSegContours = numpy.concatenate(tangentEstSegContours, axis = 1)
#print smoothedEstSegContours[z]
allTangentEstSegContoursMAG = numpy.sqrt(numpy.sum(allTangentEstSegContours * allTangentEstSegContours, axis = 0))
I = numpy.where(allTangentEstSegContoursMAG == 0)[0]
if numpy.size(I) > 0:
IDXToDelete = numpy.concatenate((I, numpy.mod(I + 1, numpy.size(allTangentEstSegContoursMAG))))
#CCSegUtils.showIMG(estSegMask)
#CCSegUtils.plotContour(allSmoothedEstSegContours)
#pylab.plot(allSmoothedEstSegContours[0, IDXToDelete], allSmoothedEstSegContours[1, IDXToDelete], 'g*')
#pylab.gcf().set_size_inches((20, 10), forward = True)
#pylab.show()
#quit()
allSmoothedEstSegContours = numpy.delete(allSmoothedEstSegContours, I, axis = 1)
allTangentEstSegContours = scipy.ndimage.filters.convolve(allSmoothedEstSegContours, tangentFilter, mode = 'wrap')
#allTangentEstSegContoursMAG =
#rint allSmoothedEstSegContours.shape
del smoothedEstSegContours
del tangentEstSegContours
# find the indices of the closest points on the estimated contours for each of the template points
# put the tempate coordinates along the X axis, estimated coordinates along the Y axis
# so therefore to evaluate distances for each template coordinate use axis = 0, to process each column
smoothedTemplateSegContourX, allSmoothedEstSegContoursX = numpy.meshgrid(numpy.atleast_2d(smoothedTemplateSegContour[0]), numpy.atleast_2d(allSmoothedEstSegContours[0]))
smoothedTemplateSegContourY, allSmoothedEstSegContoursY = numpy.meshgrid(numpy.atleast_2d(smoothedTemplateSegContour[1]), numpy.atleast_2d(allSmoothedEstSegContours[1]))
D = numpy.sqrt((smoothedTemplateSegContourX - allSmoothedEstSegContoursX) * (smoothedTemplateSegContourX - allSmoothedEstSegContoursX) + (smoothedTemplateSegContourY - allSmoothedEstSegContoursY) * (smoothedTemplateSegContourY - allSmoothedEstSegContoursY))
closestIDX = numpy.argmin(D, axis = 0)
closestDistances = D[(closestIDX, numpy.arange(D.shape[1]))]
del D
del smoothedTemplateSegContourX; del allSmoothedEstSegContoursX;
del smoothedTemplateSegContourY; del allSmoothedEstSegContoursY;
# normalise the tangents to unit magnitude, numpy does the broadcasting for us so we just need to divide by the magnitudes
#print allTangentEstSegContours
allTangentEstSegContours = allTangentEstSegContours / numpy.sqrt(numpy.sum(allTangentEstSegContours * allTangentEstSegContours, axis = 0))
# compute the dot product between template tangent vectors and those in the closest indices in the EstSegContours
dotProducts = numpy.minimum(numpy.abs(numpy.sum(numpy.take(allTangentEstSegContours, closestIDX, axis = 1) * tangentTemplateSegContour, axis = 0)), 1.0)
# clip to [0, 1]
#dotProducts = numpy.abs(dotProducts)
#dotProducts = numpy.minimum(dotProducts, 1)
return (closestDistances, dotProducts)
#dotProduct = numpy.maximum(dotProduct, -1)
#CCSegUtils.showIMG(D)
#pylab.gcf().set_size_inches((20, 10), forward = True)
#pylab.show()
#allSegMasks = numpy.zeros(estSegMask.shape)
#allSegMasks[numpy.where(numpy.logical_and(numpy.logical_not(templateSegMask), estSegMask))] = 1
#allSegMasks[numpy.where(numpy.logical_and(templateSegMask, numpy.logical_not(estSegMask)))] = 2
#allSegMasks[numpy.where(numpy.logical_and(templateSegMask, estSegMask))] = 3
#quit()
def bwJoinMSTBoundaries(BW):
assert(isinstance(BW, numpy.ndarray) and BW.dtype == numpy.bool)
# [B] = bwboundaries(BW, 8);
firstcontours, hierarchy = cv2.findContours(numpy.uint8(BW), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
del hierarchy
if len(firstcontours) == 1:
return numpy.zeros(BW.shape, dtype = numpy.bool)
else:
contours = list()
for curContour in range(len(firstcontours)):
T = numpy.atleast_2d(numpy.array(numpy.squeeze(firstcontours[curContour])))
if T.shape[0] > 1:
contours.append(T)
del firstcontours
# contourDistances contains the minimum distances contourDistances[I, J] = minimum distance between contours A and B
contourDistances = numpy.zeros((len(contours), len(contours)))
# contourMinIDXI[I, J] and contourMinIDXJ[I, J] are the indices of the elements in contours I and J, respectively that form the distance contourDistances[I, J]
contourMinIDXI = numpy.zeros((len(contours), len(contours)), dtype = numpy.uint32)
contourMinIDXJ = numpy.zeros((len(contours), len(contours)), dtype = numpy.uint32)
for contourI in range(len(contours) - 1):
for contourJ in range(contourI + 1, len(contours)):
#print contours[contourI]
#print contours[contourJ]
XI, XJ = numpy.meshgrid(numpy.take(contours[contourI], [0], axis = 1), numpy.take(contours[contourJ], [0], axis = 1))
YI, YJ = numpy.meshgrid(numpy.take(contours[contourI], [1], axis = 1), numpy.take(contours[contourJ], [1], axis = 1))
D = numpy.double((XI - XJ) * (XI - XJ) + (YI - YJ) * (YI - YJ))
I = numpy.argmin(numpy.sqrt(D))
H = numpy.unravel_index(I, XI.shape)
contourDistances[contourI, contourJ] = D[H[0], H[1]]
contourMinIDXI[contourI, contourJ] = H[1]
contourMinIDXJ[contourI, contourJ] = H[0]
del H
del XI
del XJ
del YI
del YJ
del I
del D
# CCSegUtils.showIMG(BW)
# pylab.plot(numpy.take(contours[contourI], [0], axis = 1), numpy.take(contours[contourI], [1], axis = 1), 'r')
# pylab.plot(numpy.take(contours[contourJ], [0], axis = 1), numpy.take(contours[contourJ], [1], axis = 1), 'b')
# pylab.plot(contours[contourI][H[1], 0], contours[contourI][H[1], 1], 'm*')
# pylab.plot(contours[contourJ][H[0], 0], contours[contourJ][H[0], 1], 'm*')
# pylab.show()
#print D[H[1], H[0]]
# quit()
#for contourJ in range(contourI + 1, len(contours)):
#for contourI in range(len(contours) - 1):
#contourDistances = contourDistances + contourDistances.T
#contourMinIDXI = numpy.uint32(contourMinIDXI + contourMinIDXI.T)
#contourMinIDXJ = numpy.uint32(contourMinIDXJ + contourMinIDXJ.T)
#CCSegUtils.showIMG(BW)
#contourI = 0
#contourJ = 1
#pylab.plot(numpy.take(contours[contourI], [0], axis = 1), numpy.take(contours[contourI], [1], axis = 1), 'r')
#pylab.plot(numpy.take(contours[contourJ], [0], axis = 1), numpy.take(contours[contourJ], [1], axis = 1), 'b')
# pylab.plot(AX, AY, 'm-')
# pylab.show()
if len(contours) == 2:
edges = numpy.atleast_2d(numpy.array([0, 1], dtype=numpy.uint32))
else:
# minimum spanning tree
#print contourDistances
C = scipy.sparse.csr_matrix(contourDistances, dtype = numpy.double)
MSP = scipy.sparse.csgraph.minimum_spanning_tree(C)
edges = MSP.nonzero()
edges = numpy.concatenate((numpy.atleast_2d(edges[0]), numpy.atleast_2d(edges[1])), axis = 0).T
edges = numpy.uint32(edges)
#edges = numpy.atleast_2d(numpy.array([0, 1], dtype=numpy.uint32))
#print edges
del C; del MSP;
#quit()
joiningSegments = numpy.zeros(BW.shape, dtype=numpy.bool)
# print edges.dtype
# print contourMinIDXI.dtype
for curEdge in range(edges.shape[0]):
contourI = edges[curEdge, 0]
contourJ = edges[curEdge, 1]
AX = numpy.array([contours[contourI][contourMinIDXI[contourI, contourJ], 0], contours[contourJ][contourMinIDXJ[contourI, contourJ], 0]])
AY = numpy.array([contours[contourI][contourMinIDXI[contourI, contourJ], 1], contours[contourJ][contourMinIDXJ[contourI, contourJ], 1]])
arcLength = numpy.sqrt((AX[0] - AX[1]) * (AX[0] - AX[1]) + (AY[0] - AY[1]) * (AY[0] - AY[1]))
n = numpy.ceil(arcLength * numpy.sqrt(2.0))
IX = numpy.linspace(AX[0], AX[1], n)
IY = numpy.linspace(AY[0], AY[1], n)
IX = numpy.uint32(numpy.round(IX))
IY = numpy.uint32(numpy.round(IY))
T = numpy.zeros_like(joiningSegments)
T[(IY, IX)] = True
del IX; del IY;
del n
del arcLength
del contourI; del contourJ;
Angle = numpy.arctan2(AY[1] - AY[0], AX[1] - AX[0]);
Angle = numpy.mod(Angle + 2 * numpy.pi, 2 * numpy.pi);
R = numpy.array([5, 5]) + 7 * numpy.abs(numpy.array([numpy.cos(Angle), numpy.sin(Angle)]))
AngleWeighting = -0.9 * numpy.cos(2 * (Angle + 45 * numpy.pi / 180));
SQ = numpy.sqrt(R[0] * R[1]) * AngleWeighting;
SIGMA = numpy.array([[R[0], SQ], [SQ, R[1]]])
F, FWHM = CCSegUtils.gaussianFWHM2D(SIGMA)
joiningSegments = numpy.logical_or(joiningSegments, scipy.ndimage.morphology.binary_dilation(T, structure = (F > FWHM)))
del F; del FWHM; del Angle; del R; del SQ; del SIGMA;
# [F, HalfMaximum] = gaussian_fwhm2d(SIGMA);
del AX; del AY;
#
# JoiningSegments = imdilate(T, double(F > HalfMaximum));
#
#CCSegUtils.showIMG(joiningSegments)
#pylab.show()
return joiningSegments
#quit()
# if(length(B) == 1)
# JoiningSegments = false(size(BW));
# else
#
# Distances = zeros(length(B));
# DistancesMinI = zeros(length(B));
# DistancesMinJ = zeros(length(B));
#
# for BoundaryI = 1:length(B) - 1
# for BoundaryJ = BoundaryI + 1:length(B)
# XC = bsxfun(@minus, B{BoundaryI}(:, 1), B{BoundaryJ}(:, 1)');
# YC = bsxfun(@minus, B{BoundaryI}(:, 2), B{BoundaryJ}(:, 2)');
# SZ = size(XC);
# XC = XC(:);
# YC = YC(:);
# [Distances(BoundaryI, BoundaryJ), I] = min(sqrt(XC .* XC + YC .* YC));
# [DistancesMinI(BoundaryI, BoundaryJ), DistancesMinJ(BoundaryI, BoundaryJ)] = ind2sub(SZ, I);
# end
# end
# Distances = Distances + Distances';
# DistancesMinI = DistancesMinI + DistancesMinI';
# DistancesMinJ = DistancesMinJ + DistancesMinJ';
# if(length(B) > 2)
# edges = prim(Distances);
# % this is because we calculate the distances based on increasing indices of edges
# % if the edges are returned with a greater index on the left it
# % will create errors downstream, so sort them
# edges = sort(edges, 2);
# else
# edges = [1, 2];
# end
#
# for z = 1:size(edges, 1)
# StartX = B{edges(z, 1)}(DistancesMinI(edges(z, 1), edges(z, 2)), 2);
# EndX = B{edges(z, 2)}(DistancesMinJ(edges(z, 1), edges(z, 2)), 2);
# StartY = B{edges(z, 1)}(DistancesMinI(edges(z, 1), edges(z, 2)), 1);
# EndY = B{edges(z, 2)}(DistancesMinJ(edges(z, 1), edges(z, 2)), 1);
#
# ArcLength = sqrt((StartX - EndX) * (StartX - EndX) + (StartY - EndY) * (StartY - EndY));
# n = ceil(ArcLength * sqrt(2)); % make sure we cover all pixels
#
# IX = linspace(StartX, EndX, n);
# IY = linspace(StartY, EndY, n);
# IX = round(IX);
# IY = round(IY);
# I = sub2ind(size(BW), IY, IX);
# I = unique(I);
# T = false(size(BW));
# T(I) = 1;
# Angle = atan2(EndY - StartY, EndX - StartX);
# Angle = mod(Angle + 2 * pi, 2 * pi);
#
# R = [5, 5] + 7 * abs([cos(Angle), sin(Angle)]);
#
# AngleWeighting = -0.9 * cos(2 * (Angle + 45 * pi / 180));
#
# SQ = sqrt(R(1) * R(2)) * AngleWeighting;
# SIGMA = [R(1), SQ; SQ, R(2)];
# [F, HalfMaximum] = gaussian_fwhm2d(SIGMA);
#
# JoiningSegments = imdilate(T, double(F > HalfMaximum));
#
# clear I IX IY n ArcLength EndY StartY EndX StartX F T HalfMaximum SQ Angle AngleWeighting R;
# end
# end
#
def radialStrel(R):
X, Y = numpy.meshgrid(numpy.arange(-R, R + 1), numpy.arange(-R, R + 1))
S = numpy.sqrt(X * X + Y * Y)
return (S <= R)
# retain largest component
def segCC(outputBase, groundTruthFile = None, doLK = True, doGraphics = False, segNoAuto = False, segChooseFirst = False, segGridInitPoints = False):
(outputDir, subjectID) = os.path.split(outputBase)
PNGDirectory = os.path.join(outputDir, "seg")
if doGraphics:
CCSegUtils.mkdirSafe(PNGDirectory)
# bwFillHoles test
#A = numpy.zeros((100, 100), dtype=numpy.bool)
#A[24:75, 24:75] = True
#A[39:51, 39:51] = False
#bwFillHoles(A)
#CCSegUtils.showIMG(A);
#pylab.gcf().set_size_inches((20, 10), forward = True)
#pylab.show()
#quit()
# testing interp2
#xx = numpy.arange(1, 5)
#yy = numpy.arange(1, 6)
#V = numpy.random.normal(0, 1, (yy.size, xx.size))
#xi = numpy.array([0, 1, xx[-1]])
#yi = numpy.array([0, 1, yy[-1]])
#rint V.shape
#rint xx.shape
#rint yy.shape
#F = interp2q(xx, yy, V, xi, yi)
#print F
#quit()
midSagMATFile = outputBase + "_midsag.hdf5"
assert(os.path.isfile(midSagMATFile)),"midsag hdf5 file not found"
FID = h5py.File(midSagMATFile, 'r')
NIIPixdims = numpy.array(FID['NIIPixdims'])
midSagAVW = numpy.array(FID['midSagAVW'])
#skullCrop = numpy.array(FID["skullCrop"]) # the initial cropping indices of the background
#originalOrientationString = str(numpy.array(FID['originalOrientationString']))
#originalNativeFile = str(numpy.array(FID['originalNativeFile']))
#originalNativeCroppedFile = str(numpy.array(FID['originalNativeCroppedFile']))
try:
flirtTemplateFile = str(numpy.array(FID['flirtTemplateFile']))
flirtMAT = numpy.array(FID["flirtMAT"]) # the transformation between originalNativeCroppedFile -> flirtTemplateFile
except Exception:
flirtTemplateFile = None
flirtMAT = None
#flirtCropZerosRows = numpy.array(FID["flirtCropZerosRows"])
#flirtCropZerosCols = numpy.array(FID["flirtCropZerosCols"])
#try:
# parasagittalSlices = numpy.array(FID['parasagittalSlices'])
# parasagittalFX = numpy.array(FID['parasagittalFX'])
# parasagittalFY = numpy.array(FID['parasagittalFY'])
# parasagittalFZ = numpy.array(FID['parasagittalFZ'])
#except Exception:
symNII = nibabel.load(outputBase + "_native_midsag_sym.nii.gz")
parasagittalSlices, parasagittalFX, parasagittalFY, parasagittalFZ = CCSegUtils.parasagittalSlicesAndGradients(symNII.get_data(), symNII.header.get_zooms(), numSlices = 3)
del symNII
#parasagittalSlices = None
#parasagittalFX = None
#parasagittalFY = None
#parasagittalFZ = None
#MSPMethod = str(numpy.array(FID['MSPMethod']))
midSagAVWBrainMask = numpy.logical_not(numpy.isnan(midSagAVW))
# dilate this a bit
midSagAVW[numpy.where(numpy.logical_not(midSagAVWBrainMask))] = 0
midSagAVWBrainMask = numpy.double(midSagAVWBrainMask)
#midSagAVW = midSagAVW[:, ::-1]
#midSagAVW = numpy.rot90(midSagAVW, -1)
FID.close()
del FID
# FID = h5py.File(midSagMATFile, 'w')
#
# FID.create_dataset("NIIPixdims", data=NIIPixdims, compression = 'gzip')
# FID.create_dataset("midSagAVW", data=midSagAVW, compression = 'gzip')
# FID.create_dataset("MSPMethod", data=MSPMethod)
#
# FID.close()
# return
#rint "NIIPixdims = " + str(NIIPixdims)
#CCSegUtils.showIMG(midSagAVW)
#pylab.show()
#quit()
if not groundTruthFile == None:
assert(os.path.isfile(groundTruthFile)),"Ground truth file was given, but it does not exist: " + groundTruthFile
groundTruthNII = nibabel.load(groundTruthFile)
groundTruthAVW = GroundTruthNII.get_data()
groundTruthAVW = numpy.rot90(GroundTruthAVW, 1)
#if not groundTruthFile == None:
# load atlases
scriptPath = os.path.realpath(__file__)
(scriptDir, tail) = os.path.split(scriptPath)
atlasDir = os.path.join(scriptDir, 'data')
fornixProbNII = nibabel.load(os.path.join(atlasDir, 'all_fornix_dilated_prob.nii.gz'))
fornixProbAVW = numpy.rot90(numpy.squeeze(fornixProbNII.get_data()), 1)
CCProbNII = nibabel.load(os.path.join(atlasDir, 'all_cc_prob.nii.gz'))
CCProbAVW = numpy.rot90(numpy.squeeze(CCProbNII.get_data()), 1)
templateNII = nibabel.load(os.path.join(atlasDir, 'all_msp_mean.nii.gz'))
templateAVW = numpy.rot90(numpy.squeeze(templateNII.get_data()), 1)
del atlasDir
templatePixdims = templateNII.get_header().get_zooms()[1:]
#print "midSagAVW.shape = " + str(midSagAVW.shape)
# resample to the space of the template
midSagAVWxx = numpy.arange(0, midSagAVW.shape[1]) * NIIPixdims[0]
midSagAVWxx = midSagAVWxx - numpy.mean(midSagAVWxx)
midSagAVWyy = numpy.arange(0, midSagAVW.shape[0]) * NIIPixdims[1]
midSagAVWyy = midSagAVWyy - numpy.mean(midSagAVWyy)
midSagAVWX, midSagAVWY = numpy.meshgrid(midSagAVWxx, midSagAVWyy)
templatexx = numpy.arange(0, templateAVW.shape[1]) * templatePixdims[0]
templatexx = templatexx - numpy.mean(templatexx)
templateyy = numpy.arange(0, templateAVW.shape[0]) * templatePixdims[1]
templateyy = templateyy - numpy.mean(templateyy)
# compute overlap box of midSagAVWxx, midSagAVWyy, templatexx, templateyy
lowX = numpy.maximum(midSagAVWxx[ 0], templatexx[ 0])
lowY = numpy.maximum(midSagAVWyy[ 0], templateyy[ 0])
highX = numpy.minimum(midSagAVWxx[-1], templatexx[-1])
highY = numpy.minimum(midSagAVWyy[-1], templateyy[-1])
resamplexx = numpy.arange(lowX, highX + templatePixdims[0], templatePixdims[0])
resampleyy = numpy.arange(lowY, highY + templatePixdims[1], templatePixdims[1])
#$del lowX; del lowY; del highX; del highY;
#resampleX, resampleY = numpy.meshgrid(numpy.arange(lowX, highX + templatePixdims[0], templatePixdims[0]), numpy.arange(lowY, highY + templatePixdims[1], templatePixdims[1]))
resampleX, resampleY = numpy.meshgrid(resamplexx, resampleyy)
# set up the interpolator as a function
#midSagAVWInterpolator = scipy.interpolate.interp2d(midSagAVWxx, midSagAVWyy, midSagAVW, fill_value=0)
#resampledAVW = midSagAVWInterpolator(resamplexx, resampleyy)
resampledAVW = CCSegUtils.interp2q(midSagAVWxx, midSagAVWyy, midSagAVW, resampleX, resampleY, interpmethod = 'linear', extrapval = 0)
resampledAVWBrainMask = CCSegUtils.interp2q(midSagAVWxx, midSagAVWyy, midSagAVWBrainMask, resampleX, resampleY, interpmethod = 'linear', extrapval = 0)
if not parasagittalSlices is None:
resampledSlices = list()
resampledFX = list()
resampledFY = list()
resampledFZ = list()
for z in range(parasagittalSlices.shape[2]):
resampledSlices.append(CCSegUtils.interp2q(midSagAVWxx, midSagAVWyy, parasagittalSlices[:, :, z], resampleX, resampleY, interpmethod = 'linear', extrapval = 0))
resampledFX.append(CCSegUtils.interp2q(midSagAVWxx, midSagAVWyy, parasagittalFX[:, :, z], resampleX, resampleY, interpmethod = 'linear', extrapval = 0))
resampledFY.append(CCSegUtils.interp2q(midSagAVWxx, midSagAVWyy, parasagittalFY[:, :, z], resampleX, resampleY, interpmethod = 'linear', extrapval = 0))
resampledFZ.append(CCSegUtils.interp2q(midSagAVWxx, midSagAVWyy, parasagittalFZ[:, :, z], resampleX, resampleY, interpmethod = 'linear', extrapval = 0))
parasagittalSlices = numpy.stack(resampledSlices, axis = 2)
parasagittalFX = numpy.stack(resampledFX, axis = 2)
parasagittalFY = numpy.stack(resampledFY, axis = 2)