/
ImageProcessor.java
2980 lines (2699 loc) · 93.2 KB
/
ImageProcessor.java
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
package ij.process;
import java.util.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.geom.Rectangle2D;
import java.awt.font.GlyphVector;
import java.awt.font.FontRenderContext;
import ij.gui.*;
import ij.util.*;
import ij.plugin.filter.GaussianBlur;
import ij.plugin.Binner;
import ij.plugin.Colors;
import ij.process.AutoThresholder.Method;
import ij.Prefs;
import ij.measure.Measurements;
/**
This abstract class is the superclass for classes that process
the four data types (byte, short, float and RGB) supported by ImageJ.
An ImageProcessor contains the pixel data of a 2D image and
some basic methods to manipulate it.
@see ByteProcessor
@see ShortProcessor
@see FloatProcessor
@see ColorProcessor
@see ij.ImagePlus
@see ij.ImageStack
*/
public abstract class ImageProcessor implements Cloneable {
/** Value of pixels included in masks. */
public static final int BLACK = 0xFF000000;
/** Value returned by getMinThreshold() when image is not thresholded.
* @see #isThreshold
*/
public static final double NO_THRESHOLD = -808080.0;
/** Left justify text. */
public static final int LEFT_JUSTIFY = 0;
/** Center justify text. */
public static final int CENTER_JUSTIFY = 1;
/** Right justify text. */
public static final int RIGHT_JUSTIFY = 2;
/** Isodata thresholding method */
public static final int ISODATA = 0;
/** Modified isodata method used in Image/Adjust/Threshold tool */
public static final int ISODATA2 = 1;
/** Composite image projection modes. */
public static final int UPDATE_RED=1, UPDATE_GREEN=2, UPDATE_BLUE=3, SET_FIRST_CHANNEL=4,
SUM_PROJECTION=5, MAX_PROJECTION=6, MIN_PROJECTION=7, INVERT_PROJECTION=8;
/** Interpolation methods */
public static final int NEAREST_NEIGHBOR=0, NONE=0, BILINEAR=1, BICUBIC=2;
public static final int BLUR_MORE=0, FIND_EDGES=1, MEDIAN_FILTER=2, MIN=3, MAX=4, CONVOLVE=5;
static public final int RED_LUT=0, BLACK_AND_WHITE_LUT=1, NO_LUT_UPDATE=2, OVER_UNDER_LUT=3;
static final int INVERT=0, FILL=1, ADD=2, MULT=3, AND=4, OR=5,
XOR=6, GAMMA=7, LOG=8, MINIMUM=9, MAXIMUM=10, SQR=11, SQRT=12, EXP=13, ABS=14, SET=15;
static final String WRONG_LENGTH = "width*height!=pixels.length";
int fgColor = 0;
protected int lineWidth = 1;
protected int cx, cy; //current drawing coordinates
protected Font font = ij.IJ.font12;
protected FontMetrics fontMetrics;
protected boolean antialiasedText;
protected boolean boldFont;
private static String[] interpolationMethods;
// Over/Under tresholding colors
private static int overRed, overGreen=255, overBlue;
private static int underRed, underGreen, underBlue=255;
private static boolean useBicubic;
private int sliceNumber;
private Overlay overlay;
private boolean noReset;
private boolean histogram16;
private boolean addOne;
private boolean fillColorSet;
ProgressBar progressBar;
protected int width, snapshotWidth;
protected int height, snapshotHeight;
protected int roiX, roiY, roiWidth, roiHeight;
protected int xMin, xMax, yMin, yMax;
boolean snapshotCopyMode;
ImageProcessor mask;
protected ColorModel baseCM; // base color model
protected ColorModel cm;
protected byte[] rLUT1, gLUT1, bLUT1; // base LUT
protected byte[] rLUT2, gLUT2, bLUT2; // LUT as modified by setMinAndMax and setThreshold
protected boolean interpolate; // replaced by interpolationMethod
protected int interpolationMethod = NONE;
protected double minThreshold=NO_THRESHOLD, maxThreshold=NO_THRESHOLD;
protected int histogramSize = 256;
protected double histogramMin, histogramMax;
protected float[] cTable;
protected boolean lutAnimation;
protected MemoryImageSource source; //unused
protected Image img;
protected boolean newPixels; // unused
protected Color drawingColor = Color.black;
protected int clipXMin, clipXMax, clipYMin, clipYMax; // clip rect used by drawTo, drawLine, drawDot and drawPixel
protected int justification = LEFT_JUSTIFY;
protected int lutUpdateMode;
protected WritableRaster raster;
protected BufferedImage image;
protected BufferedImage fmImage;
protected Graphics2D fmGraphics;
protected ColorModel cm2;
protected SampleModel sampleModel;
protected static IndexColorModel defaultColorModel;
protected boolean minMaxSet;
protected static double seed = Double.NaN;
protected static Random rnd;
protected void showProgress(double percentDone) {
if (progressBar!=null)
progressBar.show(percentDone);
}
/** @deprecated */
protected void hideProgress() {
showProgress(1.0);
}
/** Returns the width of this image in pixels. */
public int getWidth() {
return width;
}
/** Returns the height of this image in pixels. */
public int getHeight() {
return height;
}
/** Returns the bit depth, 8, 16, 24 (RGB) or 32. RGB images actually use 32 bits per pixel. */
public int getBitDepth() {
Object pixels = getPixels();
if (pixels==null)
return 0;
else if (pixels instanceof byte[])
return 8;
else if (pixels instanceof short[])
return 16;
else if (pixels instanceof int[])
return 24;
else if (pixels instanceof float[])
return 32;
else
return 0;
}
/** Returns this processor's color model. For non-RGB processors,
this is the base lookup table (LUT), not the one that may have
been modified by setMinAndMax() or setThreshold(). */
public ColorModel getColorModel() {
if (cm==null)
makeDefaultColorModel();
if (baseCM!=null)
return baseCM;
else
return cm;
}
private IndexColorModel getIndexColorModel() {
ColorModel cm2 = baseCM;
if (cm2==null)
cm2 = cm;
if (cm2!=null && (cm2 instanceof IndexColorModel))
return (IndexColorModel)cm2;
else
return null;
}
/** Returns the current color model, which may have
been modified by setMinAndMax() or setThreshold(). */
public ColorModel getCurrentColorModel() {
if (cm==null) makeDefaultColorModel();
return cm;
}
/** Sets the color model. Must be an IndexColorModel (aka LUT)
for all processors except the ColorProcessor. */
public void setColorModel(ColorModel cm) {
if (cm!=null && !(cm instanceof IndexColorModel))
throw new IllegalArgumentException("IndexColorModel required");
if (cm!=null && cm instanceof LUT)
cm = ((LUT)cm).getColorModel();
this.cm = cm;
baseCM = null;
rLUT1 = rLUT2 = null;
inversionTested = false;
minThreshold = NO_THRESHOLD;
}
public LUT getLut() {
ColorModel cm2 = getColorModel();
if (cm2!=null && (cm2 instanceof IndexColorModel))
return new LUT((IndexColorModel)cm2, getMin(), getMax());
else
return null;
}
public void setLut(LUT lut) {
if (lut==null)
setColorModel(null);
else {
setColorModel(lut.getColorModel());
if (lut.min!=0.0 || lut.max!=0.0)
setMinAndMax(lut.min, lut.max);
}
}
protected void makeDefaultColorModel() {
cm = getDefaultColorModel();
}
/** Inverts the values in this image's LUT (indexed color model).
Does nothing if this is a ColorProcessor. */
public void invertLut() {
IndexColorModel icm = (IndexColorModel)getColorModel();
int mapSize = icm.getMapSize();
byte[] reds = new byte[mapSize];
byte[] greens = new byte[mapSize];
byte[] blues = new byte[mapSize];
byte[] reds2 = new byte[mapSize];
byte[] greens2 = new byte[mapSize];
byte[] blues2 = new byte[mapSize];
icm.getReds(reds);
icm.getGreens(greens);
icm.getBlues(blues);
for (int i=0; i<mapSize; i++) {
reds2[i] = (byte)(reds[mapSize-i-1]&255);
greens2[i] = (byte)(greens[mapSize-i-1]&255);
blues2[i] = (byte)(blues[mapSize-i-1]&255);
}
ColorModel cm = new IndexColorModel(8, mapSize, reds2, greens2, blues2);
double min=getMin(), max=getMax();
setColorModel(cm);
setMinAndMax(min, max);
}
/** Returns the LUT index that's the best match for this color. */
public int getBestIndex(Color c) {
IndexColorModel icm;
if (cm==null)
makeDefaultColorModel();
if (minThreshold!=NO_THRESHOLD) {
double saveMin = getMinThreshold();
double saveMax = getMaxThreshold();
resetThreshold();
icm = (IndexColorModel)cm;
setThreshold(saveMin, saveMax, lutUpdateMode);
} else
icm = (IndexColorModel)cm;
int mapSize = icm.getMapSize();
byte[] rLUT = new byte[mapSize];
byte[] gLUT = new byte[mapSize];
byte[] bLUT = new byte[mapSize];
icm.getReds(rLUT);
icm.getGreens(gLUT);
icm.getBlues(bLUT);
int minDistance = Integer.MAX_VALUE;
int distance;
int minIndex = 0;
int r1 = c.getRed();
int g1 = c.getGreen();
int b1 = c.getBlue();
if (!(r1==g1&&g1==b1&&r1==b1) && icm==defaultColorModel) {
double[] w = ColorProcessor.getWeightingFactors();
r1 = (int)Math.round(3*r1*w[0]);
g1 = (int)Math.round(3*g1*w[1]);
b1 = (int)Math.round(3*b1*w[2]);
}
int r2,b2,g2;
for (int i=0; i<mapSize; i++) {
r2 = rLUT[i]&0xff; g2 = gLUT[i]&0xff; b2 = bLUT[i]&0xff;
distance = (r2-r1)*(r2-r1)+(g2-g1)*(g2-g1)+(b2-b1)*(b2-b1);
//ij.IJ.log(" "+i+" "+minIndex+" "+distance+" "+(rLUT[i]&255)+" "+(gLUT[i]&255)+" "+(bLUT[i]&255));
if (distance<minDistance) {
minDistance = distance;
minIndex = i;
}
if (minDistance==0.0)
break;
}
return minIndex;
}
protected boolean inversionTested = false;
protected boolean invertedLut;
/** Returns true if this image uses an inverting LUT
that displays zero as white and 255 as black. */
public boolean isInvertedLut() {
if (inversionTested)
return invertedLut;
IndexColorModel icm = getIndexColorModel();
if (icm==null)
return false;
boolean hasAscendingStep = false;
int v1, v2;
for (int i=1; i<255; i++) {
v1 = icm.getRed(i-1)+icm.getGreen(i-1)+icm.getBlue(i-1);
v2 = icm.getRed(i)+icm.getGreen(i)+icm.getBlue(i);
if (v1<v2) {
hasAscendingStep = true;
break;
}
}
invertedLut = !hasAscendingStep;
inversionTested = true;
return invertedLut;
}
/** Returns 'true' if this is an image with a grayscale LUT or an
* RGB image with identical red, green and blue channels.
*/
public boolean isGrayscale() {
return !isColorLut();
}
/** Returns true if this image uses a color LUT. */
public boolean isColorLut() {
IndexColorModel icm = getIndexColorModel();
if (icm==null)
return false;
int mapSize = icm.getMapSize();
byte[] reds = new byte[mapSize];
byte[] greens = new byte[mapSize];
byte[] blues = new byte[mapSize];
icm.getReds(reds);
icm.getGreens(greens);
icm.getBlues(blues);
boolean isColor = false;
for (int i=0; i<mapSize; i++) {
if ((reds[i] != greens[i]) || (greens[i] != blues[i])) {
isColor = true;
break;
}
}
return isColor;
}
/** Returns true if this image uses a pseudocolor or grayscale LUT,
in other words, is this an image that can be filtered. */
public boolean isPseudoColorLut() {
IndexColorModel icm = getIndexColorModel();
if (icm==null)
return false;
if (getMinThreshold()!=NO_THRESHOLD)
return true;
int mapSize = icm.getMapSize();
if (mapSize!=256)
return false;
byte[] reds = new byte[mapSize];
byte[] greens = new byte[mapSize];
byte[] blues = new byte[mapSize];
icm.getReds(reds);
icm.getGreens(greens);
icm.getBlues(blues);
int r, g, b, d;
int r2=reds[0]&255, g2=greens[0]&255, b2=blues[0]&255;
double sum=0.0, sum2=0.0;
for (int i=0; i<mapSize; i++) {
r=reds[i]&255; g=greens[i]&255; b=blues[i]&255;
d=r-r2; sum+=d; sum2+=d*d;
d=g-g2; sum+=d; sum2+=d*d;
d=b-b2; sum+=d; sum2+=d*d;
r2=r; g2=g; b2=b;
}
double stdDev = (768*sum2-sum*sum)/768.0;
if (stdDev>0.0)
stdDev = Math.sqrt(stdDev/(767.0));
else
stdDev = 0.0;
boolean isPseudoColor = stdDev<20.0;
if ((int)stdDev==67) isPseudoColor = true; // "3-3-2 RGB" LUT
return isPseudoColor;
}
/** Returns true if the image is using the default grayscale LUT. */
public boolean isDefaultLut() {
if (cm==null)
makeDefaultColorModel();
IndexColorModel icm = getIndexColorModel();
if (icm==null)
return false;
int mapSize = icm.getMapSize();
if (mapSize!=256)
return false;
byte[] reds = new byte[mapSize];
byte[] greens = new byte[mapSize];
byte[] blues = new byte[mapSize];
icm.getReds(reds);
icm.getGreens(greens);
icm.getBlues(blues);
boolean isDefault = true;
for (int i=0; i<mapSize; i++) {
if ((reds[i]&255)!=i || (greens[i]&255)!=i || (blues[i]&255)!=i) {
isDefault = false;
break;
}
}
return isDefault;
}
/** Sets the default fill/draw value to the pixel
value closest to the specified color. */
public abstract void setColor(Color color);
/** Sets the fill/draw color, where 'color' is
* "white", "black", "blue", etc., or a hex value
* like "#ff0000".
*/
public void setColor(String color) {
setColor(Colors.decode(color, Color.white));
}
/** Sets the background fill/draw color. */
public void setBackgroundColor(Color color) {
}
/** Sets the default fill/draw value. */
public void setColor(int value) {
setValue(value);
}
/** Sets the default fill/draw value. */
public void setColor(double value) {
setValue(value);
}
/** Sets the default fill/draw value. */
public abstract void setValue(double value);
/** Returns the default fill/draw value. */
public abstract double getForegroundValue();
/** Returns 'true' if the fill/draw value has been set in a macro. */
public boolean fillValueSet() {
return fillColorSet;
}
/** Sets the background fill value used by the rotate() and scale() methods. */
public abstract void setBackgroundValue(double value);
/** Returns the background fill value. */
public abstract double getBackgroundValue();
/** Sets the global (Color Picker) foreground color
* as the fill/draw color.
* @see ij.gui.Toolbar#setForegroundColor(Color)
* @see ij.gui.Toolbar#setForegroundValue(double)
*/
public void setGlobalForegroundColor() {
double value = Toolbar.getForegroundValue();
if (Double.isNaN(value))
setColor(Toolbar.getForegroundColor());
else
setValue(value);
}
/** Sets the global (Color Picker) background color
* as the fill/draw color.
* @see ij.gui.Toolbar#setBackgroundColor(Color)
* @see ij.gui.Toolbar#setBackgroundValue(double)
*/
public void setGlobalBackgroundColor() {
double value = Toolbar.getBackgroundValue();
if (Double.isNaN(value))
setColor(Toolbar.getBackgroundColor());
else
setValue(value);
}
/** Returns the minimum displayed pixel value. */
public abstract double getMin();
/** Returns the maximum displayed pixel value. */
public abstract double getMax();
/** This image will be displayed by mapping pixel values in the
* range min-max to screen values in the range 0-255. For
* byte images, this mapping is done by updating the LUT. For
* short and float images, it's done by generating 8-bit AWT
* images. For RGB images, it's done by changing the pixel values.
* With signed 16-bit images, use IJ.setMinAndMax(imp,min,max).
* @see ij.IJ#setMinAndMax(ij.ImagePlus,double,double)
*/
public abstract void setMinAndMax(double min, double max);
/** For short and float images, recalculates the min and max
image values needed to correctly display the image. For
ByteProcessors, resets the LUT. */
public void resetMinAndMax() {}
/** Sets the lower and upper threshold levels using NO_LUT_UPDATE. */
public void setThreshold(double minThreshold, double maxThreshold) {
setThreshold(minThreshold, maxThreshold, NO_LUT_UPDATE);
}
/** Sets the lower and upper threshold levels. The 'lutUpdate' argument
can be RED_LUT, BLACK_AND_WHITE_LUT, OVER_UNDER_LUT or NO_LUT_UPDATE.
Thresholding of RGB images is not supported. */
public void setThreshold(double minThreshold, double maxThreshold, int lutUpdate) {
//ij.IJ.log("setThreshold: "+" "+minThreshold+" "+maxThreshold+" "+lutUpdate);
if (this instanceof ColorProcessor)
return;
this.minThreshold = minThreshold;
this.maxThreshold = maxThreshold;
lutUpdateMode = lutUpdate;
if (minThreshold==NO_THRESHOLD) {
resetThreshold();
return;
}
if (lutUpdate==NO_LUT_UPDATE)
return;
if (rLUT1==null) {
if (cm==null)
makeDefaultColorModel();
baseCM = cm;
IndexColorModel m = (IndexColorModel)cm;
rLUT1 = new byte[256]; gLUT1 = new byte[256]; bLUT1 = new byte[256];
m.getReds(rLUT1); m.getGreens(gLUT1); m.getBlues(bLUT1);
rLUT2 = new byte[256]; gLUT2 = new byte[256]; bLUT2 = new byte[256];
}
int t1 = (int)minThreshold;
int t2 = (int)maxThreshold;
int index;
if (lutUpdate==RED_LUT)
for (int i=0; i<256; i++) {
if (i>=t1 && i<=t2) {
rLUT2[i] = (byte)255;
gLUT2[i] = (byte)0;
bLUT2[i] = (byte)0;
} else {
rLUT2[i] = rLUT1[i];
gLUT2[i] = gLUT1[i];
bLUT2[i] = bLUT1[i];
}
}
else if (lutUpdate==BLACK_AND_WHITE_LUT) {
// updated in v1.43i by Gabriel Lindini to use blackBackground setting
byte foreground = Prefs.blackBackground?(byte)255:(byte)0;
byte background = (byte)(255 - foreground);
for (int i=0; i<256; i++) {
if (i>=t1 && i<=t2) {
rLUT2[i] = foreground;
gLUT2[i] = foreground;
bLUT2[i] = foreground;
} else {
rLUT2[i] = background;
gLUT2[i] =background;
bLUT2[i] =background;
}
}
} else {
for (int i=0; i<256; i++) {
if (i>=t1 && i<=t2) {
rLUT2[i] = rLUT1[i];
gLUT2[i] = gLUT1[i];
bLUT2[i] = bLUT1[i];
} else if (i>t2) {
rLUT2[i] = (byte)overRed;
gLUT2[i] = (byte)overGreen;
bLUT2[i] = (byte)overBlue;
} else {
rLUT2[i] = (byte)underRed;
gLUT2[i] = (byte)underGreen;
bLUT2[i] = (byte)underBlue;
}
}
}
cm = new IndexColorModel(8, 256, rLUT2, gLUT2, bLUT2);
}
/** Automatically sets the lower and upper threshold levels, where 'method'
* must be "Default", "Huang", "Intermodes", "IsoData", "IJ_IsoData", "Li",
* "MaxEntropy", "Mean", "MinError", "Minimum", "Moments", "Otsu",
* "Percentile", "RenyiEntropy", "Shanbhag", "Triangle" or "Yen". The
* 'method' string may also include the keywords 'dark' (dark background)
* 'red' (red LUT, the default), 'b&w' (black and white LUT), 'over/under' (over/under LUT) or
* 'no-lut' (no LUT changes), for example "Huang dark b&w". The display range
* of 16-bit and 32-bit images is not reset if the 'method' string contains 'no-reset'.
* @see ImageProcessor#resetThreshold
* @see ImageProcessor#setThreshold
* @see ImageProcessor#createMask
*/
public void setAutoThreshold(String method) {
if (method==null)
throw new IllegalArgumentException("Null method");
boolean darkBackground = method.contains("dark");
noReset = method.contains("no-reset");
histogram16 = method.contains("16") && getBitDepth()==16;
addOne = !method.contains("16");
int lut = RED_LUT;
if (method.contains("b&w"))
lut = BLACK_AND_WHITE_LUT;
if (method.contains("over"))
lut = OVER_UNDER_LUT;
if (method.contains("no-lut"))
lut = NO_LUT_UPDATE;
int index = method.indexOf(" ");
if (index!=-1)
method = method.substring(0, index);
setAutoThreshold(method, darkBackground, lut);
noReset = false;
}
public void setAutoThreshold(String mString, boolean darkBackground, int lutUpdate) {
Method m = null;
try {
m = Method.valueOf(Method.class, mString);
} catch(Exception e) {
m = null;
}
if (m==null)
throw new IllegalArgumentException("Invalid method (\""+mString+"\")");
setAutoThreshold(m, darkBackground, lutUpdate);
}
public void setAutoThreshold(Method method, boolean darkBackground) {
setAutoThreshold(method, darkBackground, RED_LUT);
}
public void setAutoThreshold(Method method, boolean darkBackground, int lutUpdate) {
if (method==null || (this instanceof ColorProcessor))
return;
double min=0.0, max=0.0;
boolean notByteData = !(this instanceof ByteProcessor);
ImageProcessor ip2 = this;
if (notByteData && !histogram16) {
ImageProcessor mask = ip2.getMask();
Rectangle rect = ip2.getRoi();
if (!noReset || lutUpdate==OVER_UNDER_LUT)
ip2.resetMinAndMax();
noReset = false;
min = ip2.getMin(); max = ip2.getMax();
ip2 = ip2.convertToByte(true);
ip2.setMask(mask);
ip2.setRoi(rect);
}
ImageStatistics stats = ip2.getStats();
AutoThresholder thresholder = new AutoThresholder();
thresholder.setBilevelSubractOne(addOne);
int[] histogram = stats.histogram;
if (histogram16 && stats.histogram16!=null)
histogram = stats.histogram16;
int threshold = thresholder.getThreshold(method, histogram);
double lower, upper;
double tmax = 255.0;
if (histogram.length>256)
tmax = 65535.0;
if (darkBackground) {
if (isInvertedLut())
{lower=0.0; upper=threshold;}
else
{lower=threshold+(addOne?1:0); upper=tmax;}
} else {
if (isInvertedLut())
{lower=threshold+(addOne?1:0); upper=tmax;}
else
{lower=0.0; upper=threshold;}
}
if (histogram16)
setThreshold(lower, upper, lutUpdate);
else {
if (lower>255) lower = 255;
scaleAndSetThreshold(lower, upper, lutUpdate);
}
}
/** Automatically sets the lower and upper threshold levels, where 'method'
must be ISODATA or ISODATA2 and 'lutUpdate' must be RED_LUT,
BLACK_AND_WHITE_LUT, OVER_UNDER_LUT or NO_LUT_UPDATE.
*/
public void setAutoThreshold(int method, int lutUpdate) {
if (method<0 || method>ISODATA2)
throw new IllegalArgumentException("Invalid thresholding method");
if (this instanceof ColorProcessor)
return;
boolean notByteData = !(this instanceof ByteProcessor);
ImageProcessor ip2 = this;
if (notByteData) {
ImageProcessor mask = ip2.getMask();
Rectangle rect = ip2.getRoi();
resetMinAndMax();
ip2 = convertToByte(true);
ip2.setMask(mask);
ip2.setRoi(rect);
}
ImageStatistics stats = ip2.getStats();
int[] histogram = stats.histogram;
int originalModeCount = histogram[stats.mode];
if (method==ISODATA2) {
int maxCount2 = 0;
for (int i = 0; i<stats.nBins; i++) {
if ((histogram[i] > maxCount2) && (i!=stats.mode))
maxCount2 = histogram[i];
}
int hmax = stats.maxCount;
if ((hmax>(maxCount2 * 2)) && (maxCount2 != 0)) {
hmax = (int)(maxCount2 * 1.5);
histogram[stats.mode] = hmax;
}
}
int threshold = ip2.getAutoThreshold(stats.histogram);
histogram[stats.mode] = originalModeCount;
float[] hist = new float[256];
for (int i=0; i<256; i++)
hist[i] = stats.histogram[i];
FloatProcessor fp = new FloatProcessor(256, 1, hist, null);
GaussianBlur gb = new GaussianBlur();
gb.blur1Direction(fp, 2.0, 0.01, true, 0);
float maxCount=0f, sum=0f, mean, count;
int mode = 0;
for (int i=0; i<256; i++) {
count = hist[i];
sum += count;
if (count>maxCount) {
maxCount = count;
mode = i;
}
}
double avg = sum/256.0;
double lower, upper;
if (maxCount/avg>1.5) {
if ((stats.max-mode)>(mode-stats.min))
{lower=threshold; upper=255.0;}
else
{lower=0.0; upper=threshold;}
} else {
if (isInvertedLut())
{lower=threshold; upper=255.0;}
else
{lower=0.0; upper=threshold;}
}
scaleAndSetThreshold(lower, upper, lutUpdate);
}
/** Set the threshold using a 0-255 range. For 16-bit and 32-bit images,
* this range is taken as relative with respect to the range between the
* current display min and max, but lower=0 and upper=255 are set to the
* full-range limits of 16-bit images and -/+1e30 for float images.
*/
public void scaleAndSetThreshold(double lower, double upper, int lutUpdate) {
int bitDepth = getBitDepth();
if (bitDepth!=8 && lower!=NO_THRESHOLD) {
double min = getMin();
double max = getMax();
if (max>min) {
if (lower==0.0) {
if (bitDepth==32)
lower = Math.min(min, -1e30); // can't set to -Float.MAX_VALUE; causes FloodFiller.particleAnalyzerFill to hang;
} else
lower = min + (lower/255.0)*(max-min);
if (upper==255.0) {
if (bitDepth==16)
upper = 65535;
else if (bitDepth==32)
upper = Math.max(max, 1e30);
} else
upper = min + (upper/255.0)*(max-min);
} else
lower = upper = min;
}
setThreshold(lower, upper, lutUpdate);
}
/** Disables thresholding. */
public void resetThreshold() {
minThreshold = NO_THRESHOLD;
if (baseCM!=null) {
cm = baseCM;
baseCM = null;
}
rLUT1 = rLUT2 = null;
inversionTested = false;
}
/** Returns the lower threshold level. Returns NO_THRESHOLD
* if thresholding is not enabled.
* @see ImageProcessor#isThreshold
* @see ij.ImagePlus#isThreshold
*/
public double getMinThreshold() {
return minThreshold;
}
/** Returns the upper threshold level. */
public double getMaxThreshold() {
return maxThreshold;
}
/** Returns 'true' if this image is thresholded.
* @see ij.ImagePlus#isThreshold
*/
public boolean isThreshold() {
return getMinThreshold()!=ImageProcessor.NO_THRESHOLD;
}
/** Returns the LUT update mode, which can be RED_LUT, BLACK_AND_WHITE_LUT,
OVER_UNDER_LUT or NO_LUT_UPDATE. */
public int getLutUpdateMode() {
return lutUpdateMode;
}
/* Sets the threshold levels (non-visible) of an 8-bit mask based on
the state of Prefs.blackBackground and isInvertedLut().
@see ImageProcessor#resetBinaryThreshold
*/
public void setBinaryThreshold() {
//ij.IJ.log("setMaskThreshold1");
if (!(this instanceof ByteProcessor)) return;
double t1=255.0, t2=255.0;
boolean invertedLut = isInvertedLut();
if ((invertedLut&&ij.Prefs.blackBackground) || (!invertedLut&&!ij.Prefs.blackBackground)) {
t1 = 0.0;
t2 = 0.0;
}
//ij.IJ.log("setMaskThreshold2 "+t1+" "+t2);
setThreshold(t1, t2, ImageProcessor.NO_LUT_UPDATE);
}
/** Resets the threshold if minThreshold=maxThreshold and lutUpdateMode=NO_LUT_UPDATE.
This removes the invisible threshold set by the MakeBinary and Convert to Mask commands.
@see ImageProcessor#setBinaryThreshold
*/
public void resetBinaryThreshold() {
if (minThreshold==maxThreshold && lutUpdateMode==NO_LUT_UPDATE)
resetThreshold();
}
/** Defines a rectangular region of interest and sets the mask
to null if this ROI is not the same size as the previous one.
@see ImageProcessor#resetRoi
*/
public void setRoi(Rectangle roi) {
if (roi==null)
resetRoi();
else
setRoi(roi.x, roi.y, roi.width, roi.height);
}
/** Defines a rectangular region of interest and sets the mask to
null if this ROI is not the same size as the previous one.
@see ImageProcessor#resetRoi
*/
public void setRoi(int x, int y, int rwidth, int rheight) {
if (x<0 || y<0 || x+rwidth>width || y+rheight>height) {
//find intersection of roi and this image
Rectangle r1 = new Rectangle(x, y, rwidth, rheight);
Rectangle r2 = r1.intersection(new Rectangle(0, 0, width, height));
if (r2.width<=0 || r2.height<=0) {
roiX=0; roiY=0; roiWidth=0; roiHeight=0;
xMin=0; xMax=0; yMin=0; yMax=0;
mask=null;
return;
}
if (mask!=null && mask.getWidth()==rwidth && mask.getHeight()==rheight) {
Rectangle r3 = new Rectangle(0, 0, r2.width, r2.height);
if (x<0) r3.x = -x;
if (y<0) r3.y = -y;
mask.setRoi(r3);
if (mask!=null)
mask = mask.crop();
}
roiX=r2.x; roiY=r2.y; roiWidth=r2.width; roiHeight=r2.height;
} else {
roiX=x; roiY=y; roiWidth=rwidth; roiHeight=rheight;
}
if (mask!=null && (mask.getWidth()!=roiWidth||mask.getHeight()!=roiHeight))
mask = null;
//setup limits for 3x3 filters
xMin = Math.max(roiX, 1);
xMax = Math.min(roiX + roiWidth - 1, width - 2);
yMin = Math.max(roiY, 1);
yMax = Math.min(roiY + roiHeight - 1, height - 2);
}
/** Defines a non-rectangular region of interest that will consist of a
rectangular ROI and a mask. After processing, call <code>reset(mask)</code>
to restore non-masked pixels. Here is an example:
<pre>
ip.setRoi(new OvalRoi(50, 50, 100, 50));
ip.fill();
ip.reset(ip.getMask());
</pre>
The example assumes <code>snapshot()</code> has been called, which is the case
for code executed in the <code>run()</code> method of plugins that implement the
<code>PlugInFilter</code> interface.
@see ij.ImagePlus#getRoi
*/
public void setRoi(Roi roi) {
if (roi==null)
resetRoi();
else {
if ((roi instanceof PointRoi) && roi.size()==1) {
setMask(null);
Polygon p = roi.getPolygon();
setRoi(p.xpoints[0], p.ypoints[0], 1, 1);
} else {
setMask(roi.getMask());
setRoi(roi.getBounds());
}
}
}
/** Defines a polygonal region of interest that will consist of a
rectangular ROI and a mask. After processing, call <code>reset(mask)</code>
to restore non-masked pixels. Here is an example:
<pre>
Polygon p = new Polygon();
p.addPoint(50, 0); p.addPoint(100, 100); p.addPoint(0, 100);
ip.setRoi(triangle);
ip.invert();
ip.reset(ip.getMask());
</pre>
The example assumes <code>snapshot()</code> has been called, which is the case
for code executed in the <code>run()</code> method of plugins that implement the
<code>PlugInFilter</code> interface.
@see ij.gui.Roi#getPolygon
@see ImageProcessor#drawPolygon
@see ImageProcessor#fillPolygon
*/
public void setRoi(Polygon roi) {
if (roi==null)
{resetRoi(); return;}
Rectangle bounds = roi.getBounds();
for (int i=0; i<roi.npoints; i++) {
roi.xpoints[i] -= bounds.x;
roi.ypoints[i] -= bounds.y;
}
PolygonFiller pf = new PolygonFiller();
pf.setPolygon(roi.xpoints, roi.ypoints, roi.npoints);
ImageProcessor mask = pf.getMask(bounds.width, bounds.height);
setMask(mask);
setRoi(bounds);
for (int i=0; i<roi.npoints; i++) {
roi.xpoints[i] += bounds.x;
roi.ypoints[i] += bounds.y;
}
}
/** Sets the ROI (Region of Interest) and clipping rectangle to the entire image. */
public void resetRoi() {
roiX=0; roiY=0; roiWidth=width; roiHeight=height;
xMin=1; xMax=width-2; yMin=1; yMax=height-2;
mask=null;
clipXMin=0; clipXMax=width-1; clipYMin=0; clipYMax=height-1;
}
/** Returns a Rectangle that represents the current
region of interest. */
public Rectangle getRoi() {
return new Rectangle(roiX, roiY, roiWidth, roiHeight);
}
/** Defines a byte mask that limits processing to an
irregular ROI. Background pixels in the mask have
a value of zero. */
public void setMask(ImageProcessor mask) {
this.mask = mask;
}
/** For images with irregular ROIs, returns a mask, otherwise,
returns null. Pixels outside the mask have a value of zero. */
public ImageProcessor getMask() {
return mask;
}
/** Returns a reference to the mask pixel array, or null if there is no mask. */
public byte[] getMaskArray() {
return mask!=null?(byte[])mask.getPixels():null;
}
/** Assigns a progress bar to this processor. Set 'pb' to
null to disable the progress bar. */
public void setProgressBar(ProgressBar pb) {
progressBar = pb;
}
/** This method has been replaced by setInterpolationMethod(). */
public void setInterpolate(boolean interpolate) {
this.interpolate = interpolate;
if (interpolate)
interpolationMethod = useBicubic?BICUBIC:BILINEAR;
else
interpolationMethod = NONE;
}
/** Use this method to set the interpolation method (NONE,
BILINEAR or BICUBIC) used by scale(), resize() and rotate(). */
public void setInterpolationMethod(int method) {