1 package com.github.celldynamics.quimp.plugin.randomwalk;
2
3 import java.awt.Color;
4 import java.io.File;
5 import java.nio.file.Path;
6 import java.nio.file.Paths;
7 import java.security.InvalidParameterException;
8 import java.util.ArrayList;
9 import java.util.Arrays;
10 import java.util.List;
11 import java.util.concurrent.atomic.AtomicInteger;
12 import java.util.stream.IntStream;
13
14 import org.apache.commons.math3.linear.Array2DRowRealMatrix;
15 import org.apache.commons.math3.linear.ArrayRealVector;
16 import org.apache.commons.math3.linear.MatrixDimensionMismatchException;
17 import org.apache.commons.math3.linear.MatrixUtils;
18 import org.apache.commons.math3.linear.RealMatrix;
19 import org.apache.commons.math3.linear.RealMatrixChangingVisitor;
20 import org.apache.commons.math3.stat.StatUtils;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 import com.github.celldynamics.quimp.QuimP;
25 import com.github.celldynamics.quimp.utils.QuimPArrayUtils;
26
27 import ij.IJ;
28 import ij.ImagePlus;
29 import ij.ImageStack;
30 import ij.plugin.ImageCalculator;
31 import ij.process.BinaryProcessor;
32 import ij.process.ByteProcessor;
33 import ij.process.ImageProcessor;
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 public class RandomWalkSegmentation {
268
269
270
271
272 final int relErrStep = 20;
273
274
275
276
277
278
279
280
281
282
283 private int currentSweep = 0;
284
285
286
287
288
289
290 private int maxTheoreticalIntSqr;
291
292
293
294
295
296
297
298 private enum StoppedBy {
299
300
301
302 ITERATIONS(0),
303
304
305
306 NANS(1),
307
308
309
310 INFS(2),
311
312
313
314 RELERR(3);
315
316 private final int value;
317
318 private StoppedBy(int value) {
319 this.value = value;
320 }
321
322 public int getValue() {
323 return value;
324 }
325 }
326
327
328
329
330
331
332
333 public enum SeedTypes {
334
335
336
337
338
339 FOREGROUNDS(0),
340
341
342
343
344
345 BACKGROUND(1),
346
347
348
349
350
351
352
353 ROUGHMASK(2);
354
355
356 private final int index;
357
358
359
360
361
362
363 private SeedTypes(int index) {
364 this.index = index;
365 }
366
367
368
369
370
371
372 public int getIndex() {
373 return index;
374 }
375 }
376
377
378
379
380 static final Logger LOGGER = LoggerFactory.getLogger(RandomWalkSegmentation.class.getName());
381
382
383
384
385 public static final int RIGHT = -10;
386
387
388
389 public static final int LEFT = 10;
390
391
392
393 public static final int TOP = -01;
394
395
396
397 public static final int BOTTOM = 01;
398
399
400
401
402
403
404 private RealMatrix image;
405
406
407
408
409
410 private ImageProcessor ip;
411
412
413
414 private RandomWalkOptions params;
415
416
417
418 private ProbabilityMaps solved = null;
419
420
421
422
423
424
425
426
427 public RandomWalkSegmentation(ImageProcessor ip, RandomWalkOptions params)
428 throws RandomWalkException {
429 if (ip.getBitDepth() != 8 && ip.getBitDepth() != 16) {
430 throw new RandomWalkException("Only 8-bit or 16-bit images are supported");
431 }
432 this.ip = ip;
433 this.image = QuimPArrayUtils.imageProcessor2RealMatrix(ip);
434 this.params = params;
435 setMaxTheoreticalIntSqr(ip);
436 }
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452 public RandomWalkSegmentation(RealMatrix image, RandomWalkOptions params) {
453 this.image = image;
454 this.ip = QuimPArrayUtils.realMatrix2ImageProcessor(image);
455 this.params = params;
456 setMaxTheoreticalIntSqr(ip);
457 }
458
459
460
461
462
463
464
465
466
467
468
469
470
471 public ImageProcessor run(Seeds seeds) throws RandomWalkException {
472 LOGGER.debug("Running with options: " + params.toString());
473 if (seeds.get(SeedTypes.FOREGROUNDS) == null) {
474 return null;
475 }
476 RealMatrix[] precomputed = precomputeGradients();
477 solved = solver(seeds, precomputed);
478 if (params.intermediateFilter != null && params.gamma[1] != 0) {
479 LOGGER.debug("Running next sweep: " + params.intermediateFilter.getClass().getName());
480 Seeds seedsNext = rollNextSweep(solved);
481 if (seeds.get(SeedTypes.ROUGHMASK) != null) {
482 seedsNext.put(SeedTypes.ROUGHMASK, seeds.get(SeedTypes.ROUGHMASK, 1));
483 }
484 solved = solver(seedsNext, precomputed);
485 }
486 RealMatrix result = compare(solved);
487 ImageProcessor resultim =
488 QuimPArrayUtils.realMatrix2ImageProcessor(result).convertToByteProcessor(true);
489
490 if (params.maskLimit == true && seeds.get(SeedTypes.ROUGHMASK) != null) {
491 ImageCalculator ic = new ImageCalculator();
492 ImagePlus retc = ic.run("and create",
493 new ImagePlus("", new BinaryProcessor(
494 (ByteProcessor) seeds.get(SeedTypes.ROUGHMASK, 1).convertToByte(true))),
495 new ImagePlus("", new BinaryProcessor((ByteProcessor) resultim)));
496 resultim = retc.getProcessor();
497 }
498
499 if (params.finalFilter != null) {
500 return params.finalFilter.filter(resultim.convertToByteProcessor(true));
501 } else {
502 return resultim.convertToByteProcessor(true);
503 }
504
505 }
506
507
508
509
510
511
512
513
514 private Seeds rollNextSweep(ProbabilityMaps solved) throws RandomWalkException {
515 final double weight = 1e20;
516 Seedsamics/quimp/plugin/randomwalk/Seeds.html#Seeds">Seeds ret = new Seeds(2);
517 RealMatrix solvedWeighted;
518
519 for (int m = 0; m < solved.get(SeedTypes.FOREGROUNDS).size(); m++) {
520 solvedWeighted = solved.get(SeedTypes.FOREGROUNDS).get(m).copy();
521
522
523 solvedWeighted.walkInOptimizedOrder(
524 new MatrixCompareWeighted(solved.get(SeedTypes.BACKGROUND).get(0), weight));
525
526
527 ImageProcessor fg1 =
528 QuimPArrayUtils.realMatrix2ImageProcessor(solvedWeighted).convertToByte(true);
529
530 if (QuimP.SUPER_DEBUG) {
531 LOGGER.debug("Saving intermediate results");
532 String tmpdir = System.getProperty("java.io.tmpdir") + File.separator;
533 IJ.saveAsTiff(new ImagePlus("", fg1), tmpdir + "fg1_" + m + "_QuimP.tif");
534 }
535
536 fg1 = params.intermediateFilter.filter(fg1);
537 ret.put(SeedTypes.FOREGROUNDS, fg1);
538 }
539
540 currentSweep++;
541 solvedWeighted = solved.get(SeedTypes.BACKGROUND).get(0).copy();
542
543 double[][] fl = flatten(solved, SeedTypes.FOREGROUNDS);
544
545 solvedWeighted.walkInOptimizedOrder(
546 new MatrixCompareWeighted(MatrixUtils.createRealMatrix(fl), weight));
547 ImageProcessor bg1 =
548 QuimPArrayUtils.realMatrix2ImageProcessor(solvedWeighted).convertToByte(true);
549 if (QuimP.SUPER_DEBUG) {
550 String tmpdir = System.getProperty("java.io.tmpdir") + File.separator;
551 IJ.saveAsTiff(new ImagePlus("", bg1), tmpdir + "bg1_\"+m+\"_QuimP.tif");
552 }
553 bg1.invert();
554 bg1 = params.intermediateFilter.filter(bg1);
555 bg1.invert();
556 ret.put(SeedTypes.BACKGROUND, bg1);
557
558 return ret;
559 }
560
561
562
563
564
565
566
567
568
569 RealMatrix compare(ProbabilityMaps solved) {
570 double backgroundColorValue = 0.0;
571 double[][][] fgmaps3d = solved.convertTo3dMatrix(SeedTypes.FOREGROUNDS);
572 double[][][] bgmaps3d = solved.convertTo3dMatrix(SeedTypes.BACKGROUND);
573
574 if (fgmaps3d == null) {
575 return null;
576 }
577 int rows = fgmaps3d[0].length;
578 int cols = fgmaps3d[0][0].length;
579
580
581 if (bgmaps3d == null) {
582 bgmaps3d = new double[1][rows][cols];
583 }
584 if (rows == 0 || cols == 0 || rows != bgmaps3d[0].length || cols != bgmaps3d[0][0].length) {
585 return null;
586 }
587
588 RealMatrix ret = MatrixUtils.createRealMatrix(rows, cols);
589
590 int[][] fgMaxMap = flattenInd(fgmaps3d);
591 int[][] bgMaxMap = flattenInd(bgmaps3d);
592
593 for (int r = 0; r < rows; r++) {
594 for (int c = 0; c < cols; c++) {
595 int fi = fgMaxMap[r][c];
596 int bi = bgMaxMap[r][c];
597 if (fgmaps3d[fi][r][c] > bgmaps3d[bi][r][c]) {
598 ret.setEntry(r, c, fi + 1);
599 } else {
600 ret.setEntry(r, c, backgroundColorValue);
601 }
602 }
603 }
604 return ret;
605
606 }
607
608
609
610
611
612
613
614 private int[][] flattenInd(double[][][] in) {
615 int rows = in[0].length;
616 int cols = in[0][0].length;
617 int[][] ret = new int[rows][cols];
618
619 if (in.length == 1) {
620 return ret;
621 }
622 for (int r = 0; r < rows; r++) {
623 for (int c = 0; c < cols; c++) {
624 double max = in[0][r][c];
625 for (int z = 0; z < in.length; z++) {
626 if (in[z][r][c] > max) {
627 max = in[z][r][c];
628 ret[r][c] = z;
629 }
630 }
631 }
632 }
633 return ret;
634 }
635
636
637
638
639
640
641
642
643
644 double[][] flatten(ProbabilityMaps maps, SeedTypes key) {
645 double[][][] in = maps.convertTo3dMatrix(key);
646 if (in == null) {
647 return null;
648 }
649 int rows = in[0].length;
650 int cols = in[0][0].length;
651 double[][] ret = new double[rows][cols];
652
653 if (in.length == 1) {
654 return in[0];
655 }
656 for (int r = 0; r < rows; r++) {
657 for (int c = 0; c < cols; c++) {
658 double max = in[0][r][c];
659 for (int z = 0; z < in.length; z++) {
660 if (in[z][r][c] > max) {
661 max = in[z][r][c];
662 }
663 ret[r][c] = max;
664 }
665 }
666 }
667 return ret;
668 }
669
670
671
672
673
674
675
676
677
678
679 RealMatrix circshift(RealMatrix input, int direction) {
680
681
682
683 double[][] sub;
684 int rows = input.getRowDimension();
685 int cols = input.getColumnDimension();
686 Array2DRowRealMatrix out = new Array2DRowRealMatrix(rows, cols);
687 switch (direction) {
688 case BOTTOM:
689
690
691 sub = new double[rows][cols - 1];
692 input.copySubMatrix(0, rows - 1, 0, cols - 2, sub);
693
694 out.setSubMatrix(sub, 0, 1);
695
696 out.setColumnVector(0, input.getColumnVector(cols - 1));
697 break;
698 case TOP:
699
700
701 sub = new double[rows][cols - 1];
702 input.copySubMatrix(0, rows - 1, 1, cols - 1, sub);
703
704 out.setSubMatrix(sub, 0, 0);
705
706 out.setColumnVector(cols - 1, input.getColumnVector(0));
707 break;
708 case RIGHT:
709
710
711 sub = new double[rows - 1][cols];
712 input.copySubMatrix(1, rows - 1, 0, cols - 1, sub);
713
714 out.setSubMatrix(sub, 0, 0);
715
716 out.setRowVector(rows - 1, input.getRowVector(0));
717 break;
718 case LEFT:
719
720
721 sub = new double[rows - 1][cols];
722 input.copySubMatrix(0, rows - 2, 0, cols - 1, sub);
723
724 out.setSubMatrix(sub, 1, 0);
725
726 out.setRowVector(0, input.getRowVector(rows - 1));
727 break;
728 default:
729 throw new IllegalArgumentException("circshift: Unknown direction");
730 }
731 return out;
732 }
733
734
735
736
737
738
739
740
741 RealMatrix getSqrdDiffIntensity(RealMatrix a, RealMatrix b) {
742 RealMatrix s = a.subtract(b);
743 s.walkInOptimizedOrder(new MatrixElementPower());
744 return s;
745 }
746
747
748
749
750
751
752
753
754
755
756 private RealMatrix[] precomputeGradients() {
757
758 RealMatrix right = circshift(image, RIGHT);
759 RealMatrix top = circshift(image, TOP);
760
761 RealMatrix gradRight2 = getSqrdDiffIntensity(image, right);
762 RealMatrix gradTop2 = getSqrdDiffIntensity(image, top);
763
764 double maxGright2 = QuimPArrayUtils.getMax(gradRight2);
765 LOGGER.debug("maxGright2 " + maxGright2);
766 double maxGtop2 = QuimPArrayUtils.getMax(gradTop2);
767 LOGGER.debug("maxGtop2 " + maxGtop2);
768
769 double maxGrad2 = maxGright2 > maxGtop2 ? maxGright2 : maxGtop2;
770 LOGGER.debug("maxGrad2max " + maxGrad2);
771 if (maxGrad2 == 0) {
772 maxGrad2 = 1.0;
773 }
774
775 gradRight2.walkInOptimizedOrder(new MatrixElementDivide(maxGrad2));
776 gradTop2.walkInOptimizedOrder(new MatrixElementDivide(maxGrad2));
777
778 RealMatrix[] out = new RealMatrix[4];
779
780 RealMatrix gradLeft2 = circshift(gradRight2, LEFT);
781 out[2] = gradLeft2;
782 RealMatrix gradBottom2 = circshift(gradTop2, BOTTOM);
783 out[3] = gradBottom2;
784 out[0] = gradRight2;
785 out[1] = gradTop2;
786
787 return out;
788 }
789
790
791
792
793
794
795
796
797 protected double getMeanSeedGlobal(List<Point> seeds) {
798 return StatUtils.mean(getValues(image, seeds).getDataRef());
799 }
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819 protected RealMatrix getMeanSeedLocal(ImageProcessor mask, int localMeanMaskSize) {
820
821
822
823
824
825 if (localMeanMaskSize % 2 == 0) {
826 throw new IllegalArgumentException("Kernel sie must be odd");
827 }
828
829 if (!mask.isBinary()) {
830 throw new IllegalArgumentException("Mask must be binary");
831 }
832 if (mask.getWidth() != ip.getWidth() || mask.getHeight() != ip.getHeight()) {
833 throw new IllegalArgumentException("Mask must have size of processed image");
834 }
835 ImageProcessor maskc = mask.duplicate();
836 maskc.subtract(254);
837
838 ImageProcessor numofpix = maskc.duplicate();
839
840
841 float[] kernel = new float[localMeanMaskSize * localMeanMaskSize];
842 Arrays.fill(kernel, 1.0f);
843
844 numofpix = maskc.convertToFloat();
845 numofpix.convolve(kernel, localMeanMaskSize, localMeanMaskSize);
846 numofpix.multiply(kernel.length);
847
848 numofpix = new ImageCalculator()
849 .run("mul create", new ImagePlus("", numofpix), new ImagePlus("", maskc))
850 .getProcessor();
851
852
853
854
855 ImageProcessor cutImage = new ImageCalculator()
856 .run("mul create float", new ImagePlus("", ip), new ImagePlus("", maskc))
857 .getProcessor();
858
859 cutImage.setCalibrationTable(null);
860 cutImage.convolve(kernel, localMeanMaskSize, localMeanMaskSize);
861 cutImage.multiply(kernel.length);
862
863 cutImage = new ImageCalculator()
864 .run("mul create float", new ImagePlus("", cutImage), new ImagePlus("", maskc))
865 .getProcessor();
866
867 float[] cutImageRaw = (float[]) cutImage.getPixels();
868 for (int i = 0; i < cutImage.getPixelCount(); i++) {
869 cutImageRaw[i] = Math.round(cutImageRaw[i]);
870 }
871 float[] numofpixRaw = (float[]) numofpix.getPixels();
872 for (int i = 0; i < numofpix.getPixelCount(); i++) {
873 numofpixRaw[i] = Math.round(numofpixRaw[i]);
874 }
875
876
877 RealMatrix meanseedFg = new Array2DRowRealMatrix(cutImage.getHeight(), cutImage.getWidth());
878 int count = 0;
879 for (int r = 0; r < cutImage.getHeight(); r++) {
880 for (int c = 0; c < cutImage.getWidth(); c++) {
881 if (numofpix.getPixelValue(c, r) != 0) {
882 meanseedFg.setEntry(r, c, ((double) cutImageRaw[count] / numofpixRaw[count]));
883 } else {
884 meanseedFg.setEntry(r, c, 0.0);
885 }
886 count++;
887 }
888 }
889
890 if (QuimP.SUPER_DEBUG) {
891 LOGGER.debug("Saving intermediate results");
892 String tmpdir = System.getProperty("java.io.tmpdir") + File.separator;
893 IJ.saveAsTiff(new ImagePlus("", numofpix), tmpdir + "maskc_QuimP.tif");
894 IJ.saveAsTiff(new ImagePlus("", cutImage), tmpdir + "imagecc_QuimP.tif");
895 IJ.saveAsTiff(new ImagePlus("", QuimPArrayUtils.realMatrix2ImageProcessor(meanseedFg)),
896 tmpdir + "meanseedFg_QuimP.tif");
897 LOGGER.trace("meanseedFg M[183;289] " + meanseedFg.getEntry(183 - 1, 289 - 1));
898 LOGGER.trace("meanseedFg M[242;392] " + meanseedFg.getEntry(242 - 1, 392 - 1));
899 LOGGER.trace("cutImage M[192;279] " + cutImage.getPixelValue(279 - 1, 192 - 1));
900 }
901 return meanseedFg;
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 protected ProbabilityMaps solver(Seeds seeds, RealMatrix[] gradients) {
994 ImageStack debugPm = null;
995 RealMatrix diffIfg = null;
996
997
998 ArrayList<Integer> iterations = new ArrayList<>();
999
1000 ProbabilityMapsp/plugin/randomwalk/ProbabilityMaps.html#ProbabilityMaps">ProbabilityMaps ret = new ProbabilityMaps();
1001
1002 if (seeds.get(SeedTypes.FOREGROUNDS) == null) {
1003 return ret;
1004 }
1005
1006 List<List<Point>> seedsPointsFg = seeds.convertToList(SeedTypes.FOREGROUNDS);
1007
1008
1009
1010 List<List<Point>> userBckPoints = seeds.convertToList(SeedTypes.BACKGROUND);
1011
1012 seedsPointsFg.addAll(userBckPoints);
1013
1014
1015
1016 List<List<Point>> seedsPointsBg = new ArrayList<>();
1017
1018
1019 for (int cell = 0; cell < seedsPointsFg.size(); cell++) {
1020
1021
1022 if (seedsPointsFg.get(cell).isEmpty()) {
1023 continue;
1024 }
1025
1026 ArrayList<List<Point>> tmpSeedsPointsFg = new ArrayList<List<Point>>(seedsPointsFg);
1027 tmpSeedsPointsFg.remove(cell);
1028
1029 seedsPointsBg.clear();
1030 seedsPointsBg.addAll(tmpSeedsPointsFg);
1031
1032
1033
1034
1035 if (params.useLocalMean && seeds.get(SeedTypes.ROUGHMASK) != null
1036 && !userBckPoints.contains(seedsPointsFg.get(cell))) {
1037 RealMatrix localMeanFg =
1038 getMeanSeedLocal(seeds.get(SeedTypes.ROUGHMASK, 1), params.localMeanMaskSize);
1039 diffIfg = image.subtract(localMeanFg);
1040 } else {
1041
1042 double meanseed = getMeanSeedGlobal(seedsPointsFg.get(cell));
1043 LOGGER.debug("meanseed_fg=" + meanseed);
1044
1045 diffIfg = image.scalarAdd(-meanseed);
1046 }
1047
1048
1049 diffIfg.walkInOptimizedOrder(new MatrixElementPowerDiv(maxTheoreticalIntSqr));
1050 LOGGER.trace("fseeds size: " + seedsPointsFg.get(cell).size());
1051 LOGGER.trace("bseeds size: " + seedsPointsBg.stream().mapToInt(p -> p.size()).sum());
1052
1053
1054
1055 Array2DRowRealMatrix wrfg = (Array2DRowRealMatrix) computeweights(diffIfg, gradients[0]);
1056 Array2DRowRealMatrix wlfg = (Array2DRowRealMatrix) computeweights(diffIfg, gradients[2]);
1057 Array2DRowRealMatrix wtfg = (Array2DRowRealMatrix) computeweights(diffIfg, gradients[1]);
1058 Array2DRowRealMatrix wbfg = (Array2DRowRealMatrix) computeweights(diffIfg, gradients[3]);
1059
1060
1061
1062 RealMatrix avgwxfg = wlfg.add(wrfg);
1063 avgwxfg.walkInOptimizedOrder(new MatrixElementMultiply(0.5));
1064 RealMatrix avgwyfg = wtfg.add(wbfg);
1065 avgwyfg.walkInOptimizedOrder(new MatrixElementMultiply(0.5));
1066
1067
1068 double diffusion = getDiffusionConst(wrfg, wlfg, wtfg, wbfg, avgwxfg, avgwyfg);
1069 LOGGER.debug("D=" + diffusion);
1070
1071
1072
1073
1074 if (params.useLocalMean == false || userBckPoints.contains(seedsPointsFg.get(cell))) {
1075 wrfg.walkInOptimizedOrder(new MatrixDotProduct(avgwxfg));
1076 wlfg.walkInOptimizedOrder(new MatrixDotProduct(avgwxfg));
1077 wtfg.walkInOptimizedOrder(new MatrixDotProduct(avgwyfg));
1078 wbfg.walkInOptimizedOrder(new MatrixDotProduct(avgwyfg));
1079 }
1080
1081
1082 Array2DRowRealMatrix fg =
1083 new Array2DRowRealMatrix(image.getRowDimension(), image.getColumnDimension());
1084
1085 double[][] tmpFglast2d = new double[image.getRowDimension()][image.getColumnDimension()];
1086
1087
1088
1089 double[][] wrfg2d = wrfg.getDataRef();
1090 double[][] wlfg2d = wlfg.getDataRef();
1091 double[][] wtfg2d = wtfg.getDataRef();
1092 double[][] wbfg2d = wbfg.getDataRef();
1093
1094 double[][] fg2d = fg.getDataRef();
1095
1096 StoppedBy stoppedReason = StoppedBy.ITERATIONS;
1097 int i;
1098
1099 int iter;
1100
1101
1102
1103
1104 if (true && (userBckPoints.contains(seedsPointsFg.get(cell)) && iterations.size() > 0)) {
1105
1106 iter = iterations.stream().mapToInt(Integer::intValue).max().getAsInt();
1107
1108
1109
1110
1111
1112 iter /= (currentSweep + 1);
1113 } else {
1114 iter = params.iter / (currentSweep + 1);
1115 }
1116
1117 outerloop: for (i = 0; i < iter; i++) {
1118 if (i % relErrStep == 0) {
1119 LOGGER.info("Iter: " + i);
1120 } else {
1121 LOGGER.trace("Iter: " + i);
1122 }
1123
1124 ArrayRealVector tmp = new ArrayRealVector(1);
1125 double[] tmpref = tmp.getDataRef();
1126
1127 for (List<Point> b : seedsPointsBg) {
1128 setValues(fg, b, tmp);
1129 }
1130
1131 tmpref[0] = 1;
1132 setValues(fg, seedsPointsFg.get(cell), tmp);
1133 tmp = null;
1134
1135
1136
1137 Array2DRowRealMatrix fgcircright = (Array2DRowRealMatrix) circshift(fg, RIGHT);
1138 Array2DRowRealMatrix fgcircleft = (Array2DRowRealMatrix) circshift(fg, LEFT);
1139 Array2DRowRealMatrix fgcirctop = (Array2DRowRealMatrix) circshift(fg, TOP);
1140 Array2DRowRealMatrix fgcircbottom = (Array2DRowRealMatrix) circshift(fg, BOTTOM);
1141
1142
1143 double[][] fgcircright2d = fgcircright.getDataRef();
1144 double[][] fgcircleft2d = fgcircleft.getDataRef();
1145 double[][] fgcirctop2d = fgcirctop.getDataRef();
1146 double[][] fgcircbottom2d = fgcircbottom.getDataRef();
1147
1148 AtomicInteger at = new AtomicInteger(stoppedReason.getValue());
1149
1150
1151 int nrows = fg.getRowDimension();
1152 int ncols = fg.getColumnDimension();
1153 IntStream.range(0, nrows * ncols).parallel().forEach(ii -> {
1154 int c = ii % ncols;
1155 int r = ii / ncols;
1156 fg2d[r][c] += params.dt * (diffusion * (((fgcircright2d[r][c] - fg2d[r][c]) / wrfg2d[r][c]
1157 - (fg2d[r][c] - fgcircleft2d[r][c]) / wlfg2d[r][c])
1158 + ((fgcirctop2d[r][c] - fg2d[r][c]) / wtfg2d[r][c]
1159 - (fg2d[r][c] - fgcircbottom2d[r][c]) / wbfg2d[r][c])));
1160
1161
1162
1163 if (Double.isNaN(fg2d[r][c])) {
1164 at.set(StoppedBy.NANS.getValue());
1165 }
1166 if (Double.isInfinite(fg2d[r][c])) {
1167 at.set(StoppedBy.INFS.getValue());
1168 }
1169 });
1170
1171
1172
1173 if (stoppedReason == StoppedBy.NANS || stoppedReason == StoppedBy.INFS) {
1174 break outerloop;
1175 }
1176
1177 if ((i + 1) % relErrStep == 0) {
1178 double rele = computeRelErr(tmpFglast2d, fg2d);
1179 LOGGER.info("Relative error for object " + cell + " = " + rele);
1180 if (rele < params.relim[currentSweep]) {
1181 stoppedReason = StoppedBy.RELERR;
1182
1183 if (!userBckPoints.contains(seedsPointsFg.get(cell))) {
1184 iterations.add(i);
1185 }
1186 break outerloop;
1187 }
1188 }
1189
1190 if (QuimP.SUPER_DEBUG) {
1191 debugPm =
1192 (debugPm == null) ? new ImageStack(fg.getColumnDimension(), fg.getRowDimension())
1193 : debugPm;
1194 if (i > 1000) {
1195 if (i % 50 == 0) {
1196 debugPm.addSlice(QuimPArrayUtils.realMatrix2ImageProcessor(fg));
1197 }
1198 } else {
1199 debugPm.addSlice(QuimPArrayUtils.realMatrix2ImageProcessor(fg));
1200 }
1201 }
1202
1203 QuimPArrayUtils.copy2darray(fg2d, tmpFglast2d);
1204 }
1205 LOGGER.info("Sweep " + currentSweep + " for object " + cell + " stopped by " + stoppedReason
1206 + " after " + i + " iteration from " + iter);
1207 if (userBckPoints.contains(seedsPointsFg.get(cell))) {
1208 ret.put(SeedTypes.BACKGROUND, fg);
1209 } else {
1210 ret.put(SeedTypes.FOREGROUNDS, fg);
1211 }
1212
1213 if (QuimP.SUPER_DEBUG) {
1214 if (debugPm != null) {
1215 ImagePlus debugIm = new ImagePlus("debug", debugPm);
1216 String tmp = System.getProperty("java.io.tmpdir");
1217 Path p = Paths.get(tmp, "Rw_ProbMap-cell_" + cell);
1218 IJ.saveAsTiff(debugIm, p.toString());
1219 debugPm = null;
1220 }
1221 }
1222 }
1223 return ret;
1224 }
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235 double computeRelErr(double[][] fglast, double[][] fg) {
1236 int rows = fglast.length;
1237 int cols = fglast[0].length;
1238 double rel = 0;
1239 double tmp = 0;
1240 for (int r = 0; r < rows; r++) {
1241 for (int c = 0; c < cols; c++) {
1242 double denominator = fg[r][c] + fglast[r][c];
1243 if (denominator == 0.0) {
1244 tmp = 0.0;
1245 } else {
1246 tmp = 2 * Math.abs(fg[r][c] - fglast[r][c]) / denominator;
1247 }
1248 rel += tmp;
1249 }
1250 }
1251 double rele = rel / (rows * cols);
1252 return rele;
1253 }
1254
1255
1256
1257
1258
1259
1260
1261
1262 private RealMatrix computeweights(RealMatrix diffI2, RealMatrix grad2) {
1263 double alpha = params.alpha;
1264 double beta = params.beta;
1265 double[][] diffI2d;
1266 double[][] grad22d;
1267
1268 if (diffI2 instanceof Array2DRowRealMatrix) {
1269 diffI2d = ((Array2DRowRealMatrix) diffI2).getDataRef();
1270 } else {
1271 diffI2d = diffI2.getData();
1272 }
1273 if (grad2 instanceof Array2DRowRealMatrix) {
1274 grad22d = ((Array2DRowRealMatrix) grad2).getDataRef();
1275 } else {
1276 grad22d = grad2.getData();
1277 }
1278 Array2DRowRealMatrix w =
1279 new Array2DRowRealMatrix(diffI2.getRowDimension(), diffI2.getColumnDimension());
1280 double[][] w2d = w.getDataRef();
1281
1282 for (int r = 0; r < diffI2.getRowDimension(); r++) {
1283 for (int c = 0; c < diffI2.getColumnDimension(); c++) {
1284 w2d[r][c] = Math.exp(diffI2d[r][c] * alpha + grad22d[r][c] * beta);
1285 }
1286 }
1287
1288 return w;
1289 }
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299 private double getMinofDotProduct(RealMatrix a, RealMatrix b) {
1300 RealMatrix cp = a.copy();
1301 cp.walkInOptimizedOrder(new MatrixDotProduct(b));
1302 return QuimPArrayUtils.getMin(cp);
1303 }
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329 private double getDiffusionConst(RealMatrix wrfg, RealMatrix wlfg, RealMatrix wtfg,
1330 RealMatrix wbfg, RealMatrix avgwxfg, RealMatrix avgwyfg) {
1331
1332 double tmp1 = getMinofDotProduct(wrfg, avgwxfg);
1333 double tmp2 = getMinofDotProduct(wlfg, avgwxfg);
1334 double drl2 = tmp1 < tmp2 ? tmp1 : tmp2;
1335
1336 tmp1 = getMinofDotProduct(wtfg, avgwyfg);
1337 tmp2 = getMinofDotProduct(wbfg, avgwyfg);
1338 double dtb2 = tmp1 < tmp2 ? tmp1 : tmp2;
1339 double diffusion = drl2 < dtb2 ? drl2 : dtb2;
1340 diffusion *= 0.25;
1341 LOGGER.debug("drl2=" + drl2 + " dtb2=" + dtb2);
1342 return diffusion;
1343 }
1344
1345
1346
1347
1348
1349
1350 private void setMaxTheoreticalIntSqr(ImageProcessor ip) {
1351 switch (ip.getBitDepth()) {
1352 case 16:
1353 maxTheoreticalIntSqr = 65535 * 65535;
1354 break;
1355 case 8:
1356 default:
1357 maxTheoreticalIntSqr = 255 * 255;
1358 }
1359 }
1360
1361
1362
1363
1364
1365
1366
1367
1368 ArrayRealVector getValues(RealMatrix in, List<Point> ind) {
1369 ArrayRealVector out = new ArrayRealVector(ind.size());
1370 int l = 0;
1371 for (Point p : ind) {
1372 out.setEntry(l++, in.getEntry(p.row, p.col));
1373 }
1374 return out;
1375 }
1376
1377
1378
1379
1380
1381
1382
1383
1384 void setValues(RealMatrix in, List<Point> ind, ArrayRealVector val) {
1385 if (ind.size() != val.getDimension() && val.getDimension() != 1) {
1386 throw new InvalidParameterException(
1387 "Vector with data must contain 1 element or the same as indexes");
1388 }
1389 int delta;
1390 int l = 0;
1391 if (val.getDimension() == 1) {
1392 delta = 0;
1393 } else {
1394 delta = 1;
1395 }
1396 for (Point p : ind) {
1397 in.setEntry(p.row, p.col, val.getDataRef()[l]);
1398 l += delta;
1399 }
1400 }
1401
1402
1403
1404
1405
1406
1407 public ProbabilityMaps getProbabilityMaps() {
1408 return solved;
1409 }
1410
1411
1412
1413
1414
1415
1416
1417 static class MatrixDotSubDiv implements RealMatrixChangingVisitor {
1418
1419
1420 RealMatrix sub;
1421
1422
1423 RealMatrix div;
1424
1425
1426
1427
1428
1429
1430
1431 public MatrixDotSubDiv(RealMatrix sub, RealMatrix div) {
1432 this.sub = sub;
1433 this.div = div;
1434 }
1435
1436
1437
1438
1439
1440
1441 @Override
1442 public double end() {
1443 return 0;
1444 }
1445
1446
1447
1448
1449
1450
1451
1452 @Override
1453 public void start(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) {
1454
1455 }
1456
1457
1458
1459
1460
1461
1462 @Override
1463 public double visit(int arg0, int arg1, double arg2) {
1464
1465 return (arg2 - sub.getEntry(arg0, arg1)) / div.getEntry(arg0, arg1);
1466 }
1467
1468 }
1469
1470
1471
1472
1473
1474
1475 static class MatrixElementMultiply implements RealMatrixChangingVisitor {
1476
1477
1478 private double multiplier;
1479
1480
1481
1482
1483
1484
1485 MatrixElementMultiply(double d) {
1486 this.multiplier = d;
1487 }
1488
1489
1490
1491
1492
1493
1494 @Override
1495 public double end() {
1496 return 0;
1497 }
1498
1499
1500
1501
1502
1503
1504
1505 @Override
1506 public void start(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) {
1507 }
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517 @Override
1518 public double visit(int arg0, int arg1, double arg2) {
1519 return arg2 * multiplier;
1520 }
1521
1522 }
1523
1524
1525
1526
1527
1528
1529 static class MatrixElementDivide implements RealMatrixChangingVisitor {
1530
1531
1532 private double div;
1533
1534
1535
1536
1537
1538
1539 MatrixElementDivide(double d) {
1540 this.div = d;
1541 }
1542
1543
1544
1545
1546
1547
1548 @Override
1549 public double end() {
1550 return 0;
1551 }
1552
1553
1554
1555
1556
1557
1558
1559 @Override
1560 public void start(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) {
1561 }
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571 @Override
1572 public double visit(int arg0, int arg1, double arg2) {
1573 return arg2 / div;
1574 }
1575
1576 }
1577
1578
1579
1580
1581
1582
1583 static class MatrixElementExp implements RealMatrixChangingVisitor {
1584
1585
1586
1587
1588
1589
1590 @Override
1591 public double end() {
1592 return 0;
1593 }
1594
1595
1596
1597
1598
1599
1600
1601 @Override
1602 public void start(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) {
1603
1604 }
1605
1606
1607
1608
1609
1610
1611 @Override
1612 public double visit(int arg0, int arg1, double arg2) {
1613 return Math.exp(arg2);
1614 }
1615
1616 }
1617
1618
1619
1620
1621
1622
1623 static class MatrixElementPower implements RealMatrixChangingVisitor {
1624
1625
1626
1627
1628
1629
1630 @Override
1631 public double end() {
1632 return 0;
1633 }
1634
1635
1636
1637
1638
1639
1640
1641 @Override
1642 public void start(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) {
1643 }
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653 @Override
1654 public double visit(int arg0, int arg1, double arg2) {
1655 return arg2 * arg2;
1656 }
1657 }
1658
1659
1660
1661
1662
1663
1664
1665 static class MatrixDotProduct implements RealMatrixChangingVisitor {
1666
1667
1668 RealMatrix matrix;
1669
1670
1671
1672
1673
1674
1675 public MatrixDotProduct(RealMatrix m) {
1676 this.matrix = m;
1677 }
1678
1679
1680
1681
1682
1683
1684 @Override
1685 public double end() {
1686 return 0;
1687 }
1688
1689
1690
1691
1692
1693
1694
1695 @Override
1696 public void start(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) {
1697 if (matrix.getColumnDimension() != arg1 || matrix.getRowDimension() != arg0) {
1698 throw new MatrixDimensionMismatchException(matrix.getRowDimension(),
1699 matrix.getColumnDimension(), arg0, arg1);
1700 }
1701
1702 }
1703
1704
1705
1706
1707
1708
1709 @Override
1710 public double visit(int arg0, int arg1, double arg2) {
1711
1712 return arg2 * matrix.getEntry(arg0, arg1);
1713 }
1714
1715 }
1716
1717
1718
1719
1720
1721
1722
1723 static class MatrixDotDiv implements RealMatrixChangingVisitor {
1724
1725
1726 RealMatrix matrix;
1727
1728
1729
1730
1731
1732
1733 public MatrixDotDiv(RealMatrix m) {
1734 this.matrix = m;
1735 }
1736
1737
1738
1739
1740
1741
1742 @Override
1743 public double end() {
1744 return 0;
1745 }
1746
1747
1748
1749
1750
1751
1752
1753 @Override
1754 public void start(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) {
1755 if (matrix.getColumnDimension() != arg1 || matrix.getRowDimension() != arg0) {
1756 throw new MatrixDimensionMismatchException(matrix.getRowDimension(),
1757 matrix.getColumnDimension(), arg0, arg1);
1758 }
1759
1760 }
1761
1762
1763
1764
1765
1766
1767 @Override
1768 public double visit(int arg0, int arg1, double arg2) {
1769 return arg2 / matrix.getEntry(arg0, arg1);
1770 }
1771
1772 }
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791 static class MatrixDotDivN extends MatrixDotDiv {
1792
1793
1794
1795
1796
1797
1798 public MatrixDotDivN(RealMatrix m) {
1799 super(m);
1800 }
1801
1802
1803
1804
1805
1806
1807
1808
1809 @Override
1810 public double visit(int arg0, int arg1, double arg2) {
1811 double entry = matrix.getEntry(arg0, arg1);
1812 if (entry != 0.0) {
1813 return arg2 / matrix.getEntry(arg0, arg1);
1814 } else {
1815 return 0.0;
1816 }
1817 }
1818 }
1819
1820
1821
1822
1823
1824
1825
1826 static class MatrixCompareWeighted implements RealMatrixChangingVisitor {
1827
1828
1829 RealMatrix matrix;
1830
1831
1832 double weight;
1833
1834
1835
1836
1837
1838
1839
1840 public MatrixCompareWeighted(RealMatrix matrix, double weight) {
1841 this.matrix = matrix;
1842 this.weight = weight;
1843 }
1844
1845
1846
1847
1848
1849
1850 @Override
1851 public double end() {
1852 return 0;
1853 }
1854
1855
1856
1857
1858
1859
1860
1861 @Override
1862 public void start(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) {
1863 if (matrix.getColumnDimension() != arg1 || matrix.getRowDimension() != arg0) {
1864 throw new MatrixDimensionMismatchException(matrix.getRowDimension(),
1865 matrix.getColumnDimension(), arg0, arg1);
1866 }
1867 }
1868
1869
1870
1871
1872
1873
1874 @Override
1875 public double visit(int arg0, int arg1, double arg2) {
1876 if (arg2 > matrix.getEntry(arg0, arg1) * weight) {
1877 return 1.0;
1878 } else {
1879 return 0.0;
1880 }
1881 }
1882
1883 }
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894 static class MatrixDotAdd implements RealMatrixChangingVisitor {
1895
1896
1897 RealMatrix matrix;
1898
1899
1900
1901
1902
1903
1904 public MatrixDotAdd(RealMatrix m) {
1905 this.matrix = m;
1906 }
1907
1908
1909
1910
1911
1912
1913 @Override
1914 public double end() {
1915 return 0;
1916 }
1917
1918
1919
1920
1921
1922
1923
1924 @Override
1925 public void start(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) {
1926 if (matrix.getColumnDimension() != arg1 || matrix.getRowDimension() != arg0) {
1927 throw new MatrixDimensionMismatchException(matrix.getRowDimension(),
1928 matrix.getColumnDimension(), arg0, arg1);
1929 }
1930
1931 }
1932
1933
1934
1935
1936
1937
1938 @Override
1939 public double visit(int arg0, int arg1, double arg2) {
1940 return arg2 + matrix.getEntry(arg0, arg1);
1941 }
1942
1943 }
1944
1945
1946
1947
1948
1949
1950
1951 static class MatrixDotSub implements RealMatrixChangingVisitor {
1952
1953
1954
1955
1956
1957 RealMatrix matrix;
1958
1959
1960
1961
1962
1963
1964 public MatrixDotSub(RealMatrix m) {
1965 this.matrix = m;
1966 }
1967
1968
1969
1970
1971
1972
1973 @Override
1974 public double end() {
1975 return 0;
1976 }
1977
1978
1979
1980
1981
1982
1983
1984 @Override
1985 public void start(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) {
1986 if (matrix.getColumnDimension() != arg1 || matrix.getRowDimension() != arg0) {
1987 throw new MatrixDimensionMismatchException(matrix.getRowDimension(),
1988 matrix.getColumnDimension(), arg0, arg1);
1989 }
1990
1991 }
1992
1993
1994
1995
1996
1997
1998 @Override
1999 public double visit(int arg0, int arg1, double arg2) {
2000 return arg2 - matrix.getEntry(arg0, arg1);
2001 }
2002
2003 }
2004
2005
2006
2007
2008
2009
2010 static class MatrixElementPowerDiv implements RealMatrixChangingVisitor {
2011
2012
2013 double val;
2014
2015
2016
2017
2018
2019
2020 public MatrixElementPowerDiv(double val) {
2021 this.val = val;
2022 }
2023
2024
2025
2026
2027
2028
2029 @Override
2030 public double end() {
2031 return 0;
2032 }
2033
2034
2035
2036
2037
2038
2039
2040 @Override
2041 public void start(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) {
2042 }
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052 @Override
2053 public double visit(int arg0, int arg1, double arg2) {
2054 return (arg2 * arg2) / val;
2055 }
2056 }
2057
2058 }