-
Notifications
You must be signed in to change notification settings - Fork 1
/
LaplaceThicknessMethod.py
executable file
·1357 lines (1098 loc) · 52.9 KB
/
LaplaceThicknessMethod.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
import numpy
import numpy.linalg
import os
import errno
import matplotlib.pyplot as plt
import scipy.ndimage
import scipy.sparse.linalg
import CCSegUtils
import cv2
from inspect import stack
import skimage.measure
try:
from scikits.sparse.cholmod import cholesky
usingCholesky = True
CholeskyOfA = None
LUOfA = None
except Exception:
#print "Cholesky method not found, using LU decomposition, install scikits.sparse.cholmod"
usingCholesky = False
CholeskyOfA = None
LUOfA = None
# extrema from MATLAB
def regionPropsExtrema(BW):
pixelList = BW.nonzero()
r = pixelList[0]
c = pixelList[1]
minR = numpy.min(r);
maxR = numpy.max(r);
minC = numpy.min(c);
maxC = numpy.max(c);
minRSet = (r == minR);
maxRSet = (r == maxR);
minCSet = (c == minC);
maxCSet = (c == maxC);
#% Points 1 and 2 are on the top row.
r1 = minR;
r2 = minR;
#% Find the minimum and maximum column coordinates for
#% top-row pixels.
tmp = c[minRSet];
c1 = numpy.min(tmp);
c2 = numpy.max(tmp);
#% Points 3 and 4 are on the right column.
#% Find the minimum and maximum row coordinates for
#% right-column pixels.
tmp = r[maxCSet];
r3 = numpy.min(tmp);
r4 = numpy.max(tmp);
c3 = maxC;
c4 = maxC;
#% Points 5 and 6 are on the bottom row.
r5 = maxR;
r6 = maxR;
#% Find the minimum and maximum column coordinates for
#% bottom-row pixels.
tmp = c[maxRSet];
c5 = numpy.max(tmp);
c6 = numpy.min(tmp);
#% Points 7 and 8 are on the left column.
#% Find the minimum and maximum row coordinates for
#% left-column pixels.
tmp = r[minCSet];
r7 = numpy.max(tmp);
r8 = numpy.min(tmp);
c7 = minC;
c8 = minC;
return numpy.array([[c1, r1], [c2, r2], [c3, r3], [c4, r4], [c5, r5], [c6, r6], [c7, r7], [c8, r8]])
def contourResampleArcLength(X, n):
D = numpy.diff(X, axis = 1)
cumArcLength = numpy.cumsum(numpy.sqrt(numpy.sum(D * D, axis = 0)))
cumArcLength = cumArcLength / cumArcLength[-1]
cumArcLength = numpy.concatenate((numpy.array([0]), cumArcLength))
#print cumArcLength.shape
outContour = numpy.zeros((X.shape[0], int(n)))
for z in range(X.shape[0]):
outContour[int(z)] = numpy.interp(numpy.linspace(0, 1, int(n)), cumArcLength, X[int(z)])
return outContour
# returns the arc length of the contour in X, dimensions are the rows
def arcLength(X):
if X.shape[1] <= 1:
return 0
else:
D = numpy.diff(X, axis = 1)
return numpy.sum(numpy.sqrt(numpy.sum(D * D, axis = 0)))
def numericGradient2D(IMG, xSpacing = 1.0, ySpacing = 1.0, mask = None):
if mask is None:
T = numpy.gradient(IMG)
return (T[1], T[0])
else:
assert(numpy.array_equal(IMG.shape, mask.shape)),"IMG and mask must be the same shape"
maskIDX = numpy.where(mask)
northIDX = (numpy.maximum(maskIDX[0] - 1, 0), maskIDX[1])
southIDX = (numpy.minimum(maskIDX[0] + 1, mask.shape[0] - 1), maskIDX[1])
westIDX = (maskIDX[0], numpy.maximum(maskIDX[1] - 1, 0))
eastIDX = (maskIDX[0], numpy.minimum(maskIDX[1] + 1, mask.shape[1] - 1))
northMask = mask[northIDX]
notNorthMask = numpy.logical_not(northMask)
southMask = mask[southIDX]
notSouthMask = numpy.logical_not(southMask)
westMask = mask[westIDX]
notWestMask = numpy.logical_not(westMask)
eastMask = mask[eastIDX]
notEastMask = numpy.logical_not(eastMask)
northSouthMask = numpy.logical_and(northMask, southMask)
T = numpy.ones((numpy.count_nonzero(mask)))
T[numpy.where(northSouthMask)] = 2.0
northSouthSpacing = numpy.ones(mask.shape)
northSouthSpacing[maskIDX] = T
eastWestMask = numpy.logical_and(eastMask, westMask)
T.fill(1)
T[numpy.where(eastWestMask)] = 2.0
eastWestSpacing = numpy.ones(mask.shape)
eastWestSpacing[maskIDX] = T
del T;
# values that are north
northValues = numpy.zeros(mask.shape)
# the northValues that are in the mask should be taken from the north indices
northValues[(maskIDX[0][northMask], maskIDX[1][northMask])] = IMG[(northIDX[0][northMask], northIDX[1][northMask])]
# the northValues that are NOT in the mask should be taken from the current indices
northValues[(maskIDX[0][notNorthMask], maskIDX[1][notNorthMask])] = IMG[(maskIDX[0][notNorthMask], maskIDX[1][notNorthMask])]
# values that are south
southValues = numpy.zeros(mask.shape)
# the southValues that are in the mask should be taken from the south indices
southValues[(maskIDX[0][southMask], maskIDX[1][southMask])] = IMG[(southIDX[0][southMask], southIDX[1][southMask])]
# the southValues that are NOT in the mask should be taken from the current indices
southValues[(maskIDX[0][notSouthMask], maskIDX[1][notSouthMask])] = IMG[(maskIDX[0][notSouthMask], maskIDX[1][notSouthMask])]
# values that are west
westValues = numpy.zeros(mask.shape)
# the westValues that are in the mask should be taken from the west indices
westValues[(maskIDX[0][westMask], maskIDX[1][westMask])] = IMG[(westIDX[0][westMask], westIDX[1][westMask])]
# the westValues that are NOT in the mask should be taken from the current indices
westValues[(maskIDX[0][notWestMask], maskIDX[1][notWestMask])] = IMG[(maskIDX[0][notWestMask], maskIDX[1][notWestMask])]
# values that are east
eastValues = numpy.zeros(mask.shape)
# the eastValues that are in the mask should be taken from the east indices
eastValues[(maskIDX[0][eastMask], maskIDX[1][eastMask])] = IMG[(eastIDX[0][eastMask], eastIDX[1][eastMask])]
# the eastValues that are NOT in the mask should be taken from the current indices
eastValues[(maskIDX[0][notEastMask], maskIDX[1][notEastMask])] = IMG[(maskIDX[0][notEastMask], maskIDX[1][notEastMask])]
# plt.subplot(2, 3, 1); CCSegUtils.showIMG(northValues)
# plt.subplot(2, 3, 2); CCSegUtils.showIMG(southValues)
# plt.subplot(2, 3, 3); CCSegUtils.showIMG((southValues - northValues) / northSouthSpacing)
# plt.subplot(2, 3, 4); CCSegUtils.showIMG(westValues)
# plt.subplot(2, 3, 5); CCSegUtils.showIMG(eastValues)
# plt.subplot(2, 3, 6); CCSegUtils.showIMG((eastValues - westValues) / eastWestSpacing)
#
# plt.gcf().set_size_inches((20, 10), forward = True)
# plt.show()
# quit()
return ((eastValues - westValues) / eastWestSpacing, (southValues - northValues) / northSouthSpacing)
#function [MaskInnerBoundary, ...
# MaskOuterBoundary, ...
# MaskFree, ...
# SolvedImage, ...
# XY, ...
# X, ...
# Y, ...
# NormFX, ...
# NormFY, ...
# ValidStreamlines, ...
# StartV, ...
# MaskClosed] = laplace_get_points_2d_auto_mw(xi, yi, xo, yo, XScale, YScale, Delta, NumStreamlines, MaskClosedPrecomputed)
def laplaceEquationResetFactors():
global CholeskyOfA
global LUOfA
CholeskyOfA = None
LUOfA = None
# python port of laplace_get_points_2d_auto_mw.m
def laplaceEquation2DContours(xi, yi, xo, yo, xScale, yScale, delta, numStreamlines, onlyNeedStartV = False, redoFactorisation = False):
displayMessages = False
contoursBoundingBox = dict()
contoursBoundingBox['minX'] = numpy.min(numpy.concatenate((xi, xo), axis = 1))
contoursBoundingBox['maxX'] = numpy.max(numpy.concatenate((xi, xo), axis = 1))
contoursBoundingBox['minY'] = numpy.min(numpy.concatenate((yi, yo), axis = 1))
contoursBoundingBox['maxY'] = numpy.max(numpy.concatenate((yi, yo), axis = 1))
xx = numpy.arange(numpy.floor(contoursBoundingBox['minX']) - 1, numpy.ceil(contoursBoundingBox['maxX']) + 1 + 1, 1.0 / delta) * xScale
yy = numpy.arange(numpy.floor(contoursBoundingBox['minY']) - 1, numpy.ceil(contoursBoundingBox['maxY']) + 1 + 1, 1.0 / delta) * yScale
#print xx
#print yy
X, Y = numpy.meshgrid(xx, yy)
scaledxi = xi * xScale
scaledyi = yi * yScale
scaledxo = xo * xScale
scaledyo = yo * yScale
xSpacing = xx[1] - xx[0]
ySpacing = yy[1] - yy[0]
#if not onlyNeedStartV:
# print contoursBoundingBox
# print xx[0]
# print xx[-1]
# print yy[0]
# print yy[-1]
# resample the contours veensely to rasterise them
arcLengthI = arcLength(numpy.concatenate((scaledxi, scaledyi), axis = 0))
arcLengthO = arcLength(numpy.concatenate((scaledxo, scaledyo), axis = 0))
contourIResampled = contourResampleArcLength(numpy.concatenate((scaledxi, scaledyi), axis = 0), numpy.ceil(arcLengthI) * 10)
contourOResampled = contourResampleArcLength(numpy.concatenate((scaledxo, scaledyo), axis = 0), numpy.ceil(arcLengthO) * 10)
del arcLengthI; del arcLengthO;
XI = numpy.atleast_2d(contourIResampled[0])
YI = numpy.atleast_2d(contourIResampled[1])
XO = numpy.atleast_2d(contourOResampled[0])
YO = numpy.atleast_2d(contourOResampled[1])
# find the nearest pixel of each of the XI, YI, XO, YO
XIColumns = numpy.int32(numpy.round((XI - xx[0]) / xSpacing))
XOColumns = numpy.int32(numpy.round((XO - xx[0]) / xSpacing))
YIRows = numpy.int32(numpy.round((YI - yy[0]) / ySpacing))
YORows = numpy.int32(numpy.round((YO - yy[0]) / ySpacing))
#print X.shape
maskInnerBoundary = numpy.zeros(X.shape, dtype = numpy.bool)
maskOuterBoundary = numpy.zeros(X.shape, dtype = numpy.bool)
maskInnerBoundary[(YIRows, XIColumns)] = True
maskOuterBoundary[(YORows, XOColumns)] = True
del YIRows; del YORows; del XIColumns; del XOColumns;
del contourOResampled; del contourIResampled;
arcLengthI = arcLength(numpy.concatenate((scaledxi, scaledyi), axis = 0))
arcLengthO = arcLength(numpy.concatenate((scaledxo, scaledyo), axis = 0))
#rint numpy.array([[scaledxi[0, 0]], [scaledyi[0, 0]]]).shape
closedContour = numpy.concatenate((numpy.concatenate((scaledxi, scaledyi), axis = 0), numpy.concatenate((scaledxo, scaledyo), axis = 0), numpy.array([[scaledxi[0, 0]], [scaledyi[0, 0]]])), axis = 1)
closedContourResampled = contourResampleArcLength(closedContour, numpy.ceil(arcLength(closedContour)) * 10)
#print closedContour.shape
#print closedContourResampled.shape
closedColumns = numpy.int32(numpy.round((closedContourResampled[0] - xx[0]) / xSpacing))
closedRows = numpy.int32(numpy.round((closedContourResampled[1] - yy[0]) / ySpacing))
maskClosed = numpy.zeros(X.shape, dtype = numpy.bool)
maskClosed[(closedRows, closedColumns)] = True
del closedContour
del closedContourResampled
del closedColumns
del closedRows
#if not onlyNeedStartV:
# CCSegUtils.showIMG(maskClosed)
# CSegUtils.plotContour(closedContour)
# plt.gcf().set_size_inches((20, 10), forward = True)
# plt.show()
# quit()
#maskClosed = scipy.ndimage.morphology.binary_fill_holes(numpy.logical_or(maskInnerBoundary, maskOuterBoundary), structure = numpy.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]], dtype = numpy.bool))
maskClosed = scipy.ndimage.morphology.binary_fill_holes(maskClosed, structure = numpy.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]], dtype = numpy.bool))
maskFree = numpy.logical_and(maskClosed, numpy.logical_not(numpy.logical_or(maskInnerBoundary, maskOuterBoundary)))
# if not onlyNeedStartV:
#
# plt.subplot(2, 2, 1); CCSegUtils.showIMG(maskInnerBoundary, extent = [xx[0], xx[-1], yy[0], yy[-1]])#plt.imshow(maskInnerBoundary, extent = [xx[0], xx[-1], yy[0], yy[-1]], origin = 'lower') #CCSegUtils.showIMG(maskInnerBoundary)
# lineProps = {'color': 'r', 'linewidth': 2}
# #CCSegUtils.plotContour(numpy.concatenate((XI, YI), axis = 0), lineProps = lineProps, closed = False);
# CCSegUtils.plotContour(numpy.concatenate((scaledxi, scaledyi), axis = 0), lineProps = lineProps, closed = False);
# lineProps = {'color': 'g', 'linewidth': 2}
# CCSegUtils.plotContour(numpy.concatenate((scaledxo, scaledyo), axis = 0), lineProps = lineProps, closed = False);
# plt.subplot(2, 2, 2); CCSegUtils.showIMG(maskOuterBoundary, extent = [xx[0], xx[-1], yy[0], yy[-1]])
# lineProps = {'color': 'b', 'linewidth': 2}
# CCSegUtils.plotContour(numpy.concatenate((XO, YO), axis = 0), lineProps = lineProps, closed = False);
# plt.subplot(2, 2, 3); CCSegUtils.showIMG(numpy.logical_or(maskInnerBoundary, maskOuterBoundary), extent = [xx[0], xx[-1], yy[0], yy[-1]])
# plt.subplot(2, 2, 4); CCSegUtils.showIMG(maskClosed, extent = [xx[0], xx[-1], yy[0], yy[-1]])
#
# plt.gcf().set_size_inches((20, 10), forward = True)
# plt.show()
# quit()
# plt.subplot(2, 2, 3); CCSegUtils.showIMG(numpy.logical_or(maskInnerBoundary, maskOuterBoundary), extent = [xx[0], xx[-1], yy[0], yy[-1]])
#
# plt.subplot(2, 2, 3); CCSegUtils.showIMG(maskClosed, extent = [xx[0], xx[-1], yy[0], yy[-1]])
# plt.subplot(2, 2, 4); CCSegUtils.showIMG(maskFree, extent = [xx[0], xx[-1], yy[0], yy[-1]])
#
del XI; del YI; del XO; del YO;
# we now have maskFree (to be solved), maskInnerBoundary, maskOuterBoundary
################ SET UP LAPLACE EQUATIONS
innerPotential = 0
outerPotential = 1
numVariables = numpy.sum(maskFree)
variableIDXIMG = numpy.zeros(X.shape, dtype = numpy.int32)
variableIDXIMG.fill(-1)
# try to get the matlab ordering for comparison
#variableIDXIMG = variableIDXIMG.T
n = -1
variableIDXIMG = numpy.rot90(variableIDXIMG, n)
maskFree = numpy.rot90(maskFree, n)
variableIDXIMG[numpy.where(maskFree)] = numpy.arange(numVariables)
variableIDXIMG = numpy.rot90(variableIDXIMG, -n)
maskFree = numpy.rot90(maskFree, -n)
del n
#plt.subplot(1, 2, 1); CCSegUtils.showIMG(maskFree)
#plt.subplot(1, 2, 2); CCSegUtils.showIMG(variableIDXIMG)
#plt.gcf().set_size_inches((20, 10), forward = True)
#plt.show()
#quit()
laplaceBVector = numpy.zeros((numVariables))
#numNeighbours = numpy.zeros_like(laplaceBVector)
#CCSegUtils.showIMG(variableIDXIMG, extent = [xx[0], xx[-1], yy[0], yy[-1]])
maskFreeIDX = numpy.where(maskFree)
#T = numpy.concatenate((numpy.zeros_like(maskFreeIDX[0]), numpy.zeros_like(maskFreeIDX[0]) + 1, numpy.zeros_like(maskFreeIDX[0]) + 2))
#maskFreeIDXForRGB = (numpy.tile(maskFreeIDX[0], (3)), numpy.tile(maskFreeIDX[1], (3)), T)
#del T
# try to do this in python
northNeighbours = (maskFreeIDX[0] - 1, maskFreeIDX[1])
southNeighbours = (maskFreeIDX[0] + 1, maskFreeIDX[1])
westNeighbours = (maskFreeIDX[0], maskFreeIDX[1] - 1)
eastNeighbours = (maskFreeIDX[0], maskFreeIDX[1] + 1)
northNeighboursVariables = variableIDXIMG[northNeighbours]
southNeighboursVariables = variableIDXIMG[southNeighbours]
westNeighboursVariables = variableIDXIMG[westNeighbours]
eastNeighboursVariables = variableIDXIMG[eastNeighbours]
global CholeskyOfA
global LUOfA
global usingCholesky
#print redoFactorisation
if (CholeskyOfA == None and LUOfA == None) or redoFactorisation == True:
#print "factorising"
# we havent got anything precomputed so make the A matrix
# make the laplaceAMatrix
# we use a lil_matrix because we are changing the sparsity structure, the lil_matrix is efficient at this
laplaceAMatrix = scipy.sparse.lil_matrix((numVariables, numVariables), dtype=numpy.double)
northNeighboursOtherVariables = numpy.where(northNeighboursVariables != -1)
southNeighboursOtherVariables = numpy.where(southNeighboursVariables != -1)
westNeighboursOtherVariables = numpy.where(westNeighboursVariables != -1)
eastNeighboursOtherVariables = numpy.where(eastNeighboursVariables != -1)
# for the north/south neighbours of I
# if we see another variable J, set laplaceAMatrix[I, J] = -xSpacingSquared
# if we see one of the inner boundary pixels, add xSpacingSquared * innerPotential to laplaceBVector[I]
# if we see one of the outer boundary pixels, add xSpacingSquared * outerPotential to laplaceBVector[I]
# neighbours are other variables
# the I is the collection of variables whose neighbours have variable indices
# the J is the indices of the other variables
I = variableIDXIMG[(maskFreeIDX[0][northNeighboursOtherVariables], maskFreeIDX[1][northNeighboursOtherVariables])]
J = northNeighboursVariables[northNeighboursOtherVariables]
laplaceAMatrix[(I, J)] = -(xSpacing * xSpacing)
del I; del J;
# neighbours are other variables
# the I is the collection of variables whose neighbours have variable indices
# the J is the indices of the other variables
I = variableIDXIMG[(maskFreeIDX[0][southNeighboursOtherVariables], maskFreeIDX[1][southNeighboursOtherVariables])]
J = southNeighboursVariables[southNeighboursOtherVariables]
laplaceAMatrix[(I, J)] = -(xSpacing * xSpacing)
del I; del J;
# for the east/west neighbours of I
# if we see another variable J, set laplaceAMatrix[I, J] = -ySpacingSquared
# if we see one of the inner boundary pixels, add ySpacingSquared * innerPotential to laplaceBVector[I]
# if we see one of the outer boundary pixels, add ySpacingSquared * outerPotential to laplaceBVector[I]
# neighbours are other variables
# the I is the collection of variables whose neighbours have variable indices
# the J is the indices of the other variables
I = variableIDXIMG[(maskFreeIDX[0][westNeighboursOtherVariables], maskFreeIDX[1][westNeighboursOtherVariables])]
J = westNeighboursVariables[westNeighboursOtherVariables]
laplaceAMatrix[(I, J)] = -(ySpacing * ySpacing)
del I; del J;
# neighbours are other variables
# the I is the collection of variables whose neighbours have variable indices
# the J is the indices of the other variables
I = variableIDXIMG[(maskFreeIDX[0][eastNeighboursOtherVariables], maskFreeIDX[1][eastNeighboursOtherVariables])]
J = eastNeighboursVariables[eastNeighboursOtherVariables]
laplaceAMatrix[(I, J)] = -(ySpacing * ySpacing)
del I; del J;
# do the diagonal, it equals 2 * xSpacingSquared + 2 * ySpacingSquared
laplaceAMatrix[(numpy.arange(numVariables), numpy.arange(numVariables))] = 2.0 * (xSpacing * xSpacing + ySpacing * ySpacing)
if usingCholesky:
try:
CholeskyOfA = cholesky(laplaceAMatrix.tocsc())
LUOfA = None
except Exception:
LUOfA = scipy.sparse.linalg.splu(scipy.sparse.csc_matrix(laplaceAMatrix))
CholeskyOfA = None
#Z = L(laplaceBVector)
#del L
else:# except Exception:
LUOfA = scipy.sparse.linalg.splu(scipy.sparse.csc_matrix(laplaceAMatrix))
CholeskyOfA = None
#Z = LUofA.solve(laplaceBVector)
#del LUofA
del laplaceAMatrix
del northNeighboursOtherVariables
del southNeighboursOtherVariables
del westNeighboursOtherVariables
del eastNeighboursOtherVariables
#elif laplaceCholeskyDecompPrecomputed != None and laplaceLUDecompPrecomputed == None:
# CholeskyOfA = laplaceCholeskyDecompPrecomputed
# LUOfA = None
#elif laplaceCholeskyDecompPrecomputed == None and laplaceLUDecompPrecomputed != None:
# LUOfA = laplaceLUDecompPrecomputed
# CholeskyOfA = None
northNeighboursInnerBoundary = numpy.where(maskInnerBoundary[northNeighbours])
northNeighboursOuterBoundary = numpy.where(maskOuterBoundary[northNeighbours])
# neighbours are on inner boundary
# the I is the collection of free indices that are on the boundary
# increment the B vector xSpacingSquared * innerPotential
I = variableIDXIMG[(maskFreeIDX[0][northNeighboursInnerBoundary], maskFreeIDX[1][northNeighboursInnerBoundary])]
laplaceBVector[(I)] = laplaceBVector[(I)] + (xSpacing * xSpacing) * innerPotential
del I;
# neighbours are on outer boundary
# the I is the collection of free indices that are on the boundary
# increment the B vector xSpacingSquared * outerPotential
I = variableIDXIMG[(maskFreeIDX[0][northNeighboursOuterBoundary], maskFreeIDX[1][northNeighboursOuterBoundary])]
laplaceBVector[(I)] = laplaceBVector[(I)] + (xSpacing * xSpacing) * outerPotential
del I;
del northNeighboursInnerBoundary; del northNeighboursOuterBoundary;
# do the south neighbours
southNeighboursInnerBoundary = numpy.where(maskInnerBoundary[southNeighbours])
southNeighboursOuterBoundary = numpy.where(maskOuterBoundary[southNeighbours])
# neighbours are on inner boundary
# the I is the collection of free indices that are on the boundary
# increment the B vector xSpacingSquared * innerPotential
I = variableIDXIMG[(maskFreeIDX[0][southNeighboursInnerBoundary], maskFreeIDX[1][southNeighboursInnerBoundary])]
laplaceBVector[(I)] = laplaceBVector[(I)] + (xSpacing * xSpacing) * innerPotential
del I;
# neighbours are on outer boundary
# the I is the collection of free indices that are on the boundary
# increment the B vector xSpacingSquared * outerPotential
I = variableIDXIMG[(maskFreeIDX[0][southNeighboursOuterBoundary], maskFreeIDX[1][southNeighboursOuterBoundary])]
laplaceBVector[(I)] = laplaceBVector[(I)] + (xSpacing * xSpacing) * outerPotential
del I;
del southNeighboursInnerBoundary; del southNeighboursOuterBoundary;
# do the west neighbours
westNeighboursInnerBoundary = numpy.where(maskInnerBoundary[westNeighbours])
westNeighboursOuterBoundary = numpy.where(maskOuterBoundary[westNeighbours])
# neighbours are on inner boundary
# the I is the collection of free indices that are on the boundary
# increment the B vector xSpacingSquared * innerPotential
I = variableIDXIMG[(maskFreeIDX[0][westNeighboursInnerBoundary], maskFreeIDX[1][westNeighboursInnerBoundary])]
laplaceBVector[(I)] = laplaceBVector[(I)] + (ySpacing * ySpacing) * innerPotential
del I;
# neighbours are on outer boundary
# the I is the collection of free indices that are on the boundary
# increment the B vector xSpacingSquared * outerPotential
I = variableIDXIMG[(maskFreeIDX[0][westNeighboursOuterBoundary], maskFreeIDX[1][westNeighboursOuterBoundary])]
laplaceBVector[(I)] = laplaceBVector[(I)] + (ySpacing * ySpacing) * outerPotential
del I;
del westNeighboursInnerBoundary; del westNeighboursOuterBoundary;
# do the east neighbours
eastNeighboursInnerBoundary = numpy.where(maskInnerBoundary[eastNeighbours])
eastNeighboursOuterBoundary = numpy.where(maskOuterBoundary[eastNeighbours])
# neighbours are on inner boundary
# the I is the collection of free indices that are on the boundary
# increment the B vector xSpacingSquared * innerPotential
I = variableIDXIMG[(maskFreeIDX[0][eastNeighboursInnerBoundary], maskFreeIDX[1][eastNeighboursInnerBoundary])]
laplaceBVector[(I)] = laplaceBVector[(I)] + (ySpacing * ySpacing) * innerPotential
del I;
# neighbours are on outer boundary
# the I is the collection of free indices that are on the boundary
# increment the B vector xSpacingSquared * outerPotential
I = variableIDXIMG[(maskFreeIDX[0][eastNeighboursOuterBoundary], maskFreeIDX[1][eastNeighboursOuterBoundary])]
laplaceBVector[(I)] = laplaceBVector[(I)] + (ySpacing * ySpacing) * outerPotential
del I;
del eastNeighboursInnerBoundary; del eastNeighboursOuterBoundary;
del northNeighbours; del southNeighbours; del eastNeighbours; del westNeighbours;
#import time
#t = time.time()
# do stuff
#print laplaceAMatrix.shape
#L = scipy.linalg.cholesky(laplaceAMatrix.todense())
#LUofA = scipy.sparse.linalg.splu(scipy.sparse.csc_matrix(laplaceAMatrix))
#print LS
#print laplaceBVector
#elapsed = time.time() - t
#print "LU: " + str(elapsed)
#print usingCholesky
#elapsed = time.time() - t
#print "CHOL: " + str(elapsed)
#import LinAlgHelpers
# my implementation was too slow
#print "Starting Chol"
#t = time.time()
#ZL = LinAlgHelpers.chol(laplaceAMatrix)
#print "Finished Chol"
#Z1 = LinAlgHelpers.substituteSolve(ZL, laplaceBVector)
#Z = LinAlgHelpers.substituteSolve(ZL.T, Z1)
#elapsed = time.time() - t
#print "My CHOL: " + str(elapsed)
#laplaceCholeskyDecompPrecomputed = None, laplaceLUDecompPrecomputed = None
#quit()
if not CholeskyOfA is None:
#if laplaceCholeskyDecompPrecomputed != None:
# CholeskyOfA
Z = CholeskyOfA(laplaceBVector)
#del L
else:
#if laplaceLUDecompPrecomputed != None:
# LUOfA = laplaceLUDecompPrecomputed
#print LUOfA
#print laplaceBVector
#print laplaceLUDecompPrecomputed
Z = LUOfA.solve(laplaceBVector)
#del LUOfA
#if not onlyNeedStartV:
# print Z
del laplaceBVector
solvedImage = numpy.zeros(maskFree.shape)
solvedImage[numpy.where(maskInnerBoundary)] = innerPotential
solvedImage[numpy.where(maskOuterBoundary)] = outerPotential
solvedImage[numpy.where(maskFree)] = Z[variableIDXIMG[numpy.where(maskFree)]]
solvedImage[numpy.where(numpy.logical_not(maskClosed))] = numpy.nan
#if not onlyNeedStartV:
# solvedImage[numpy.where(numpy.logical_not(maskFree))] = 0
#print solvedImage[numpy.where(maskFree)]
#if not onlyNeedStartV:
# CCSegUtils.showIMG(solvedImage, extent = [xx[0], xx[-1], yy[0], yy[-1]])
# plt.colorbar()
# plt.gcf().set_size_inches((20, 10), forward = True)
# plt.show()
# quit()
# the gradients get normalised but this is to take into account possible different x to y sizes
FX, FY = numericGradient2D(solvedImage, xSpacing = xSpacing, ySpacing = ySpacing, mask = maskClosed)
# normalise the gradients
gradMAG = numpy.sqrt(FX * FX + FY * FY)
gradMAG[numpy.where(gradMAG == 0)] = 1
FX = FX / gradMAG
FY = FY / gradMAG
del gradMAG
#plt.subplot(1, 2, 1); CCSegUtils.showIMG(FX, extent = [xx[0], xx[-1], yy[0], yy[-1]])
#plt.subplot(1, 2, 2); CCSegUtils.showIMG(FY, extent = [xx[0], xx[-1], yy[0], yy[-1]])
#if numStreamlines > 0:
C = skimage.measure.find_contours(solvedImage, 0.5)
outC = list()
for z in range(len(C)):
if C[z].shape[0] > 2:
#print C[z].shape
I = numpy.where(numpy.all(numpy.isfinite(C[z]), axis = 1))
# print I
T = numpy.atleast_2d(numpy.flipud(numpy.squeeze(numpy.take(C[z], I, axis = 0)).T))
if T.shape[1] > 2:
outC.append(T)
del T
del I
if len(outC) > 1:
# choose the largest one
#print "Warning more than one isocontour, picking largest one"
maxSZ = 0
maxIDX = 0
for z in range(len(outC)):
if outC[z].shape[1] > maxSZ:
maxSZ = outC[z].shape[1]
maxIDX = z
startV = numpy.array(outC[maxIDX])
else:
startV = numpy.array(outC[0])
# print len(outC)
# for z in range(len(outC)):
# print outC[z].shape
# plt.plot(outC[z][0], outC[z][1])
#CCSegUtils.showIMG(solvedImage)
# plt.gcf().set_size_inches((20, 10), forward = True)
# plt.show()
#assert(len(outC) == 1),"More than one midpoint isocontour"
if onlyNeedStartV:
return startV
#rint startV
del outC; del C;
startV = contourResampleArcLength(startV, numStreamlines)
startV[0] = numpy.interp(startV[0], numpy.arange(numpy.size(xx)), xx)
startV[1] = numpy.interp(startV[1], numpy.arange(numpy.size(yy)), yy)
#% fix to avoid oscillation at boundaries
#% pad the gradient at the boundaries
SE = numpy.ones((3, 3), dtype = numpy.bool)
I = numpy.where(maskClosed)
oldFX = numpy.array(FX)
oldFY = numpy.array(FY)
S = scipy.ndimage.morphology.grey_dilation(FX, footprint = SE)
S[I] = 0;
T = scipy.ndimage.morphology.grey_erosion(FX, footprint = SE)
T[I] = 0;
FX = FX + S + T;
S = scipy.ndimage.morphology.grey_dilation(FY, footprint = SE);
S[I] = 0;
T = scipy.ndimage.morphology.grey_erosion(FY, footprint = SE)
T[I] = 0;
FY = FY + S + T;
# plt.subplot(2, 2, 1); CCSegUtils.showIMG(oldFX, extent = [xx[0], xx[-1], yy[0], yy[-1]])
# lineProps = {'color': 'r', 'linewidth': 2}
# CCSegUtils.plotContour(numpy.concatenate((XI, YI), axis = 0), lineProps = lineProps, closed = False);
# lineProps = {'color': 'b', 'linewidth': 2}
# CCSegUtils.plotContour(numpy.concatenate((XO, YO), axis = 0), lineProps = lineProps, closed = False);
# lineProps = {'color': 'g', 'linewidth': 2}
# CCSegUtils.plotContour(startV, lineProps = lineProps, closed = False);
# plt.subplot(2, 2, 2); CCSegUtils.showIMG(oldFY, extent = [xx[0], xx[-1], yy[0], yy[-1]])
# lineProps = {'color': 'r', 'linewidth': 2}
# CCSegUtils.plotContour(numpy.concatenate((XI, YI), axis = 0), lineProps = lineProps, closed = False);
# lineProps = {'color': 'b', 'linewidth': 2}
# CCSegUtils.plotContour(numpy.concatenate((XO, YO), axis = 0), lineProps = lineProps, closed = False);
# lineProps = {'color': 'g', 'linewidth': 2}
# CCSegUtils.plotContour(startV, lineProps = lineProps, closed = False);
#
#
#plt.subplot(2, 2, 3); CCSegUtils.showIMG(FX, extent = [xx[0], xx[-1], yy[0], yy[-1]])
# lineProps = {'color': 'r', 'linewidth': 2}
# CCSegUtils.plotContour(numpy.concatenate((XI, YI), axis = 0), lineProps = lineProps, closed = False);
# lineProps = {'color': 'b', 'linewidth': 2}
# CCSegUtils.plotContour(numpy.concatenate((XO, YO), axis = 0), lineProps = lineProps, closed = False);
# lineProps = {'color': 'g', 'linewidth': 2}
# CCSegUtils.plotContour(startV, lineProps = lineProps, closed = False);
# plt.subplot(2, 2, 4); CCSegUtils.showIMG(FY, extent = [xx[0], xx[-1], yy[0], yy[-1]])
# lineProps = {'color': 'r', 'linewidth': 2}
# CCSegUtils.plotContour(numpy.concatenate((XI, YI), axis = 0), lineProps = lineProps, closed = False);
# lineProps = {'color': 'b', 'linewidth': 2}
# CCSegUtils.plotContour(numpy.concatenate((XO, YO), axis = 0), lineProps = lineProps, closed = False);
# lineProps = {'color': 'g', 'linewidth': 2}
# CCSegUtils.plotContour(startV, lineProps = lineProps, closed = False);
#for z in range(len(outC)):
#print outC[z].shape
#CCSegUtils.showIMG(solvedImage)
#CCSegUtils.plotContour(outC[0], closed = False)
## STREAMLINE PART ###
sxi = numpy.interp(startV[0], xx, numpy.arange(numpy.size(xx)))
syi = numpy.interp(startV[1], yy, numpy.arange(numpy.size(yy)))
import Streamline2DCython
#plt.subplot(2, 2, 1); CCSegUtils.showIMG(oldFX)
#plt.subplot(2, 2, 2); CCSegUtils.showIMG(oldFY)
#plt.subplot(2, 2, 3); CCSegUtils.showIMG(FX); plt.plot(sxi, syi, 'g-');
#plt.subplot(2, 2, 4); CCSegUtils.showIMG(FY); plt.plot(sxi, syi, 'g-');
#plt.gcf().set_size_inches((20, 10), forward = True)
#plt.show()
#print xx.shape
#print yy.shape
#print FX.shape
#print FY.shape
#print xx[0]
#print xx[-1]
streamlinesOuter = list()
streamlinesInner = list()
streamlinesOuterIntersected = list()
streamlinesInnerIntersected = list()
#streamlinesOuter = [None,] * 100
#streamlinesInner = [None,] * 100
#z = 50
#streamlinesInner[z] = Streamline2DCython.streamline2D(xx, yy, -FX, -FY, sxi[z], syi[z], 0.2, 10000, numpy.ravel(scaledxi), numpy.ravel(scaledyi))
#streamline = [None,] * 100
for z in range(numpy.size(sxi)):
#for z in numpy.array([0.000, 14.000, 22.000, 78.000, 99.000], dtype = numpy.int):
#print "Contour " + str(z)
T, I = Streamline2DCython.streamline2D(xx, yy, -FX, -FY, sxi[z], syi[z], 0.2, 10000, numpy.ravel(scaledxi), numpy.ravel(scaledyi))
streamlinesOuter.append(numpy.array(T))
streamlinesOuterIntersected.append(I)
del I
del T
T, I = Streamline2DCython.streamline2D(xx, yy, FX, FY, sxi[z], syi[z], 0.2, 10000, numpy.ravel(scaledxo), numpy.ravel(scaledyo))
streamlinesInner.append(numpy.array(T))
streamlinesInnerIntersected.append(I)
del I
del T
streamlinesOuterIntersected = numpy.array(streamlinesOuterIntersected)
streamlinesOuterIntersected = (streamlinesOuterIntersected == 1)
streamlinesInnerIntersected = numpy.array(streamlinesInnerIntersected)
streamlinesInnerIntersected = (streamlinesInnerIntersected == 1)
validStreamlines = numpy.logical_and(streamlinesOuterIntersected, streamlinesInnerIntersected)
streamlines = list()
#print len(streamlinesInner)
#print len(streamlinesOuter)
for z in range(len(streamlinesInner)):
streamlines.append(numpy.concatenate((numpy.fliplr(streamlinesInner[z][:, 1:]), streamlinesOuter[z]), axis = 1))
# CCSegUtils.showIMG(FX, extent = [xx[0], xx[-1], yy[0], yy[-1]], ticks = True);
#for z in range(len(streamlines)):
# lineProps = {'color': 'b', 'linewidth': 2}
# CCSegUtils.plotContour(streamlines[z], closed = False, lineProps = lineProps)
#CCSegUtils.plotContour(streamlinesOuter[z], closed = False)
#CCSegUtils.plotContour(streamlinesInner[z], closed = False)
#lineProps = {'color': 'g', 'linewidth': 2}
#plt.plot(scaledxi[0], scaledyi[0], **lineProps)
#lineProps = {'color': 'r', 'linewidth': 2}
#plt.plot(scaledxo[0], scaledyo[0], **lineProps)
#
# plt.subplot(1, 2, 2); CCSegUtils.showIMG(FY, extent = [xx[0], xx[-1], yy[0], yy[-1]], ticks = True);
# for z in range(numpy.size(sxi)):
# CCSegUtils.plotContour(streamlinesOuter[z], closed = False)
# CCSegUtils.plotContour(streamlinesInner[z], closed = False)
# plt.plot(scaledxi[0], scaledyi[0])
# plt.plot(scaledxo[0], scaledyo[0])
#print scaledxi
#print scaledyi
# CCSegUtils.showIMG(FX)
#plt.gca().invert_yaxis()
#plt.gcf().set_size_inches((20, 10), forward = True)
#plt.show()
scaledContours = dict()
scaledContours['inner'] = numpy.concatenate((scaledxi, scaledyi), axis = 0)
scaledContours['outer'] = numpy.concatenate((scaledxo, scaledyo), axis = 0)
return (xx, yy, scaledContours, streamlines, validStreamlines, solvedImage)
#quit()
#plt.gcf().set_size_inches((20, 10), forward = True)
#plt.show()
#quit()
# for the
#print I
#maskRGB = numpy.double(numpy.concatenate((numpy.atleast_3d(maskFree), numpy.atleast_3d(maskInnerBoundary), numpy.atleast_3d(maskOuterBoundary)), axis = 2))
#
#plt.subplot(2, 2, 1); CCSegUtils.showIMG(maskRGB, extent = [xx[0], xx[-1], yy[0], yy[-1]])
#
#T = numpy.array(maskRGB)
#B = numpy.zeros_like(maskFree)
#for z in range(len(I)):
# B = numpy.logical_or(B, variableIDXIMG == I[(z)])
#B = B[numpy.where(maskFree)]
#T[maskFreeIDXForRGB] = numpy.tile(B, (3))
#plt.subplot(2, 2, 2); CCSegUtils.showIMG(T, extent = [xx[0], xx[-1], yy[0], yy[-1]]); plt.title('Other neighbours')
#
# T = numpy.array(maskRGB)
# T[maskFreeIDXForRGB] = numpy.tile(innerBoundaryIDX, (3))
# plt.subplot(2, 2, 3); CCSegUtils.showIMG(T, extent = [xx[0], xx[-1], yy[0], yy[-1]]); plt.title('Inner boundary')
#
# T = numpy.array(maskRGB)
# T[maskFreeIDXForRGB] = numpy.tile(outerBoundaryIDX, (3))
# plt.subplot(2, 2, 4); CCSegUtils.showIMG(T, extent = [xx[0], xx[-1], yy[0], yy[-1]]); plt.title('Inner boundary')
#
# for the east/west neighbours of I
# if we see another variable J, set laplaceAMatrix[I, J] = -ySpacingSquared
# if we see one of the inner boundary pixels, add ySpacingSquared * innerPotential to laplaceBVector[I]
# if we see one of the outer boundary pixels, add ySpacingSquared * outerPotential to laplaceBVector[I]
# for the north/south neighbours
# if we see another variable, set laplaceAMatrix[I, J] = -ySpacingSquared
# if we see for the north neighbours, if we see another variable, set laplaceAMatrix[I, J] = -xSpacingSquared
# numNeighbours = 2 * xSpacingSquared + 2 * ySpacingSquared
#closedHighResContour = numpy.concatenate
#print XI.shape
#print YI
#del contourIResampled; del contourOResampled;
#plt.plot(BWContour[0, leftStart + curLeftOffset], BWContour[1, leftStart + curLeftOffset], 'b*');
#print curContours['xi']
#plt.gca().invert_yaxis()
#quit()
def endpointsFindObjectiveFunction(BWContour, leftOffset, rightOffset, rightStartIDX):
# make the contour start from the current leftOffset
BWContourLeftOffset = numpy.roll(BWContour, -leftOffset, axis = 1)
curContours = dict()
#print BWContourLeftOffset.shape
# the "inner" contour is from the start to the current left offset, we subtract the left offset because we have shifted the contour
curContours['xi'] = numpy.atleast_2d(BWContourLeftOffset[0, 0:(rightStartIDX - leftOffset + rightOffset + 1)])
curContours['yi'] = numpy.atleast_2d(BWContourLeftOffset[1, 0:(rightStartIDX - leftOffset + rightOffset + 1)])
# the "outer" contour is from the end of the inner contour to the end
curContours['xo'] = numpy.atleast_2d(BWContourLeftOffset[0, (rightStartIDX - leftOffset + rightOffset + 1):])
curContours['yo'] = numpy.atleast_2d(BWContourLeftOffset[1, (rightStartIDX - leftOffset + rightOffset + 1):])
#if rightOffset > 1:
# lineProps = {'color': 'r', 'linewidth': 2}
# CCSegUtils.plotContour(numpy.concatenate((curContours['xi'], curContours['yi']), axis = 0), lineProps = lineProps, closed = False);
# lineProps = {'color': 'b', 'linewidth': 2}
# CCSegUtils.plotContour(numpy.concatenate((curContours['xo'], curContours['yo']), axis = 0), lineProps = lineProps, closed = False);
#plt.plot(BWContour[0, leftStart + curLeftOffset], BWContour[1, leftStart + curLeftOffset], 'b*');
#print curContours['xi']
#plt.gcf().set_size_inches((20, 10), forward = True)
# plt.title(str(rightOffset))
# plt.show()
#quit()
#plt.subplot(1, 2, 2); CCSegUtils.showIMG(maskClosed);
startV = laplaceEquation2DContours(curContours['xi'], curContours['yi'], curContours['xo'][::-1], curContours['yo'][::-1], 1.0, 1.0, 1.0, 0, onlyNeedStartV = True)
#print startV
arcLength = numpy.sum(numpy.sqrt(numpy.sum(numpy.diff(startV, axis = 1) * numpy.diff(startV, axis = 1), axis = 0)))
#print arcLength
return arcLength
def contourClockwise(BW, BWContour):
paddedBW = numpy.pad(BW, (1, 1), mode = 'constant', constant_values = 0)
TBWContour = BWContour + 1
T = numpy.roll(BWContour, -1, axis = 1) - BWContour
#T = T + 1
clockwiseArray = numpy.zeros((BWContour.shape[1]))
for z in range(BWContour.shape[1]):
# get the orientations
if T[0, z] < 0 and T[1, z] < 0: # up-left
if paddedBW[TBWContour[1, z] + 1, TBWContour[0, z] - 1]:
# the left hand side of this vector is down-left
clockwiseArray[z] = -1
elif paddedBW[TBWContour[1, z] - 1, TBWContour[0, z] + 1]:
# the right hand side of this vector is up-right
clockwiseArray[z] = 1
elif T[0, z] == 0 and T[1, z] < 0: # up
if paddedBW[TBWContour[1, z], TBWContour[0, z] - 1]:
# the left hand side of this vector is left
clockwiseArray[z] = -1
elif paddedBW[TBWContour[1, z], TBWContour[0, z] + 1]:
# the right hand side of this vector is right
clockwiseArray[z] = 1
elif T[0, z] > 0 and T[1, z] < 0: # up-right
if paddedBW[TBWContour[1, z] - 1, TBWContour[0, z] - 1]:
# the left hand side of this vector is up-left
clockwiseArray[z] = -1
elif paddedBW[TBWContour[1, z] + 1, TBWContour[0, z] + 1]:
# the right hand side of this vector is down-right
clockwiseArray[z] = 1
elif T[0, z] < 0 and T[1, z] == 0: # left
if paddedBW[TBWContour[1, z] + 1, TBWContour[0, z]]:
# the left hand side of this vector is down
clockwiseArray[z] = -1
elif paddedBW[TBWContour[1, z] - 1, TBWContour[0, z]]:
# the right hand side of this vector is up
clockwiseArray[z] = 1
elif T[0, z] > 0 and T[1, z] == 0: # right
if paddedBW[TBWContour[1, z] - 1, TBWContour[0, z]]:
# the left hand side of this vector is up
clockwiseArray[z] = -1
elif paddedBW[TBWContour[1, z] + 1, TBWContour[0, z]]:
# the right hand side of this vector is down
clockwiseArray[z] = 1
elif T[0, z] < 0 and T[1, z] > 0: # down-left
if paddedBW[TBWContour[1, z] + 1, TBWContour[0, z] + 1]:
# the left hand side of this vector is down-right
clockwiseArray[z] = -1
elif paddedBW[TBWContour[1, z] - 1, TBWContour[0, z] - 1]:
# the right hand side of this vector is up-left
clockwiseArray[z] = 1
elif T[0, z] == 0 and T[1, z] > 0: # down
if paddedBW[TBWContour[1, z], TBWContour[0, z] + 1]:
# the left hand side of this vector is right
clockwiseArray[z] = -1
elif paddedBW[TBWContour[1, z], TBWContour[0, z] - 1]:
# the right hand side of this vector is left
clockwiseArray[z] = 1
elif T[0, z] > 0 and T[1, z] > 0: # down-right
if paddedBW[TBWContour[1, z] - 1, TBWContour[0, z] + 1]:
# the left hand side of this vector is up-right
clockwiseArray[z] = -1
elif paddedBW[TBWContour[1, z] + 1, TBWContour[0, z] - 1]:
# the right hand side of this vector is down-left
clockwiseArray[z] = 1
#print clockwiseArray
#CCSegUtils.showIMG(BW)
#plt.plot(BWContour[0], BWContour[1], 'r-')
#I = numpy.where(clockwiseArray == -1); plt.quiver(BWContour[0, I], BWContour[1, I], T[0, I], T[1, I], color = 'r', angles = 'xy')
#I = numpy.where(clockwiseArray == 1); plt.quiver(BWContour[0, I], BWContour[1, I], T[0, I], T[1, I], color = 'g', angles = 'xy')
#plt.show()
#quit()
clockwiseVotes = numpy.size(numpy.where(clockwiseArray == 1))
anticlockwiseVotes = numpy.size(numpy.where(clockwiseArray == -1))
if clockwiseVotes > anticlockwiseVotes:
return "clockwise"
elif clockwiseVotes < anticlockwiseVotes:
return "anticlockwise"
else:
return None