forked from imagej/ImageJ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImagePlus.java
3297 lines (3054 loc) · 98.4 KB
/
ImagePlus.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;
import java.awt.*;
import java.awt.image.*;
import java.net.URL;
import java.util.*;
import ij.process.*;
import ij.io.*;
import ij.gui.*;
import ij.measure.*;
import ij.plugin.filter.Analyzer;
import ij.util.*;
import ij.macro.Interpreter;
import ij.plugin.*;
import ij.plugin.frame.*;
/**
An ImagePlus contain an ImageProcessor (2D image) or an ImageStack (3D, 4D or 5D image).
It also includes metadata (spatial calibration and possibly the directory/file where
it was read from). The ImageProcessor contains the pixel data (8-bit, 16-bit, float or RGB)
of the 2D image and some basic methods to manipulate it. An ImageStack is essentually
a list ImageProcessors of same type and size.
@see ij.process.ImageProcessor
@see ij.ImageStack
@see ij.gui.ImageWindow
@see ij.gui.ImageCanvas
*/
public class ImagePlus implements ImageObserver, Measurements, Cloneable {
/** 8-bit grayscale (unsigned)*/
public static final int GRAY8 = 0;
/** 16-bit grayscale (unsigned) */
public static final int GRAY16 = 1;
/** 32-bit floating-point grayscale */
public static final int GRAY32 = 2;
/** 8-bit indexed color */
public static final int COLOR_256 = 3;
/** 32-bit RGB color */
public static final int COLOR_RGB = 4;
/** Title of image used by Flatten command */
public static final String flattenTitle = "flatten~canvas";
/** True if any changes have been made to this image. */
public boolean changes;
protected Image img;
protected ImageProcessor ip;
protected ImageWindow win;
protected Roi roi;
protected int currentSlice; // current stack index (one-based)
protected static final int OPENED=0, CLOSED=1, UPDATED=2;
protected boolean compositeImage;
protected int width;
protected int height;
protected boolean locked;
private int lockedCount;
private Thread lockingThread;
protected int nChannels = 1;
protected int nSlices = 1;
protected int nFrames = 1;
protected boolean dimensionsSet;
private ImageJ ij = IJ.getInstance();
private String title;
private String url;
private FileInfo fileInfo;
private int imageType = GRAY8;
private boolean typeSet;
private ImageStack stack;
private static int currentID = -1;
private int ID;
private static Component comp;
private boolean imageLoaded;
private int imageUpdateY, imageUpdateW;
private Properties properties;
private long startTime;
private Calibration calibration;
private static Calibration globalCalibration;
private boolean activated;
private boolean ignoreFlush;
private boolean errorLoadingImage;
private static ImagePlus clipboard;
private static Vector listeners = new Vector();
private boolean openAsHyperStack;
private int[] position = {1,1,1};
private boolean noUpdateMode;
private ImageCanvas flatteningCanvas;
private Overlay overlay;
private boolean compositeChanges;
private boolean hideOverlay;
private static int default16bitDisplayRange;
private boolean antialiasRendering = true;
private boolean ignoreGlobalCalibration;
private boolean oneSliceStack;
public boolean setIJMenuBar = Prefs.setIJMenuBar;
private Plot plot;
private Properties imageProperties;
/** Constructs an uninitialized ImagePlus. */
public ImagePlus() {
title = (this instanceof CompositeImage)?"composite":"null";
setID();
}
/** Constructs an ImagePlus from an Image or BufferedImage. The first
argument will be used as the title of the window that displays the image.
Throws an IllegalStateException if an error occurs while loading the image. */
public ImagePlus(String title, Image image) {
this.title = title;
if (image!=null)
setImage(image);
setID();
}
/** Constructs an ImagePlus from an ImageProcessor. */
public ImagePlus(String title, ImageProcessor ip) {
setProcessor(title, ip);
setID();
}
/** Constructs an ImagePlus from a TIFF, BMP, DICOM, FITS,
PGM, GIF or JPRG specified by a path or from a TIFF, DICOM,
GIF or JPEG specified by a URL. */
public ImagePlus(String pathOrURL) {
Opener opener = new Opener();
ImagePlus imp = null;
boolean isURL = pathOrURL.indexOf("://")>0;
if (isURL)
imp = opener.openURL(pathOrURL);
else
imp = opener.openImage(pathOrURL);
if (imp!=null) {
if (imp.getStackSize()>1)
setStack(imp.getTitle(), imp.getStack());
else
setProcessor(imp.getTitle(), imp.getProcessor());
setCalibration(imp.getCalibration());
properties = imp.getProperties();
setFileInfo(imp.getOriginalFileInfo());
setDimensions(imp.getNChannels(), imp.getNSlices(), imp.getNFrames());
setOverlay(imp.getOverlay());
setRoi(imp.getRoi());
if (isURL)
this.url = pathOrURL;
setID();
}
}
/** Constructs an ImagePlus from a stack. */
public ImagePlus(String title, ImageStack stack) {
setStack(title, stack);
setID();
}
private void setID() {
ID = --currentID;
}
/** Locks the image so other threads can test to see if it is in use.
* One thread can lock an image multiple times, then it has to unlock
* it as many times until it is unlocked. This allows nested locking
* within a thread.
* Returns true if the image was successfully locked.
* Beeps, displays a message in the status bar, and returns
* false if the image is already locked by another thread.
*/
public synchronized boolean lock() {
return lock(true);
}
/** Similar to lock, but doesn't beep and display an error
* message if the attempt to lock the image fails.
*/
public synchronized boolean lockSilently() {
return lock(false);
}
private synchronized boolean lock(boolean loud) {
if (locked) {
if (Thread.currentThread()==lockingThread) {
lockedCount++; //allow locking multiple times by the same thread
return true;
} else {
if (loud) {
IJ.beep();
IJ.showStatus("\"" + title + "\" is locked");
if (IJ.debugMode) IJ.log(title + " is locked by " + lockingThread + "; refused locking by " + Thread.currentThread().getName());
if (IJ.macroRunning())
IJ.wait(500);
}
return false;
}
} else {
locked = true; //we could use 'lockedCount instead, but subclasses might use
lockedCount = 1;
lockingThread = Thread.currentThread();
if (win instanceof StackWindow)
((StackWindow)win).setSlidersEnabled(false);
if (IJ.debugMode) IJ.log(title + ": locked" + (loud ? "" : "silently") + " by " + Thread.currentThread().getName());
return true;
}
}
/** Unlocks the image.
* In case the image had been locked several times by the current thread,
* it gets unlocked only after as many unlock operations as there were
* previous lock operations.
*/
public synchronized void unlock() {
if (Thread.currentThread()==lockingThread && lockedCount>1)
lockedCount--;
else {
locked = false;
lockedCount = 0;
lockingThread = null;
if (win instanceof StackWindow)
((StackWindow)win).setSlidersEnabled(true);
if (IJ.debugMode) IJ.log(title + ": unlocked");
}
}
/** Returns 'true' if the image is locked. */
public boolean isLocked() {
return locked;
}
/** Returns 'true' if the image was locked on another thread. */
public boolean isLockedByAnotherThread() {
return locked && Thread.currentThread()!=lockingThread;
}
private void waitForImage(Image image) {
if (comp==null) {
comp = IJ.getInstance();
if (comp==null)
comp = new Canvas();
}
imageLoaded = false;
if (!comp.prepareImage(image, this)) {
double progress;
waitStart = System.currentTimeMillis();
while (!imageLoaded && !errorLoadingImage) {
IJ.wait(30);
if (imageUpdateW>1) {
progress = (double)imageUpdateY/imageUpdateW;
if (!(progress<1.0)) {
progress = 1.0 - (progress-1.0);
if (progress<0.0) progress = 0.9;
}
showProgress(progress);
}
}
showProgress(1.0);
}
}
long waitStart;
private void showProgress(double percent) {
if ((System.currentTimeMillis()-waitStart)>500L)
IJ.showProgress(percent);
}
/** Draws the image. If there is an ROI, its
outline is also displayed. Does nothing if there
is no window associated with this image (i.e. show()
has not been called).*/
public void draw() {
if (win!=null)
win.getCanvas().repaint();
}
/** Draws image and roi outline using a clip rect. */
public void draw(int x, int y, int width, int height){
if (win!=null) {
ImageCanvas ic = win.getCanvas();
double mag = ic.getMagnification();
x = ic.screenX(x);
y = ic.screenY(y);
width = (int)(width*mag);
height = (int)(height*mag);
ic.repaint(x, y, width, height);
if (listeners.size()>0 && roi!=null && roi.getPasteMode()!=Roi.NOT_PASTING)
notifyListeners(UPDATED);
}
}
/** Updates this image from the pixel data in its
associated ImageProcessor, then displays it. Does
nothing if there is no window associated with
this image (i.e. show() has not been called).*/
public synchronized void updateAndDraw() {
if (stack!=null && !stack.isVirtual() && currentSlice>=1 && currentSlice<=stack.size()) {
if (stack.size()>1 && win!=null && !(win instanceof StackWindow)) {
setStack(stack); //adds scroll bar if stack size has changed to >1
return;
}
Object pixels = stack.getPixels(currentSlice);
if (ip!=null && pixels!=null && pixels!=ip.getPixels()) { // was stack updated?
try {
ip.setPixels(pixels);
ip.setSnapshotPixels(null);
} catch(Exception e) {}
}
}
if (win!=null) {
win.getCanvas().setImageUpdated();
if (listeners.size()>0) notifyListeners(UPDATED);
}
draw();
}
/** Use to update the image when the underlying virtual stack changes. */
public void updateVirtualSlice() {
ImageStack vstack = getStack();
if (vstack.isVirtual()) {
double min=getDisplayRangeMin(), max=getDisplayRangeMax();
setProcessor(vstack.getProcessor(getCurrentSlice()));
setDisplayRange(min,max);
} else
throw new IllegalArgumentException("Virtual stack required");
}
/** Sets the display mode of composite color images, where 'mode'
should be IJ.COMPOSITE, IJ.COLOR or IJ.GRAYSCALE. */
public void setDisplayMode(int mode) {
if (this instanceof CompositeImage) {
((CompositeImage)this).setMode(mode);
updateAndDraw();
}
}
/** Returns the display mode (IJ.COMPOSITE, IJ.COLOR
or IJ.GRAYSCALE) if this is a composite color
image, or 0 if it not. */
public int getDisplayMode() {
if (this instanceof CompositeImage)
return ((CompositeImage)this).getMode();
else
return 0;
}
/** Controls which channels in a composite color image are displayed,
where 'channels' is a list of ones and zeros that specify the channels to
display. For example, "101" causes channels 1 and 3 to be displayed. */
public void setActiveChannels(String channels) {
if (!(this instanceof CompositeImage))
return;
boolean[] active = ((CompositeImage)this).getActiveChannels();
for (int i=0; i<active.length; i++) {
boolean b = false;
if (channels.length()>i && channels.charAt(i)=='1')
b = true;
active[i] = b;
}
updateAndDraw();
Channels.updateChannels();
}
/** Updates this image from the pixel data in its
associated ImageProcessor, then displays it.
The CompositeImage class overrides this method
to only update the current channel. */
public void updateChannelAndDraw() {
updateAndDraw();
}
/** Returns a reference to the current ImageProcessor. The
CompositeImage class overrides this method to return
the processor associated with the current channel. */
public ImageProcessor getChannelProcessor() {
return getProcessor();
}
/** Returns an array containing the lookup tables used by this image,
* one per channel, or an empty array if this is an RGB image.
* @see #getNChannels
* @see #isComposite
* @see #getCompositeMode
*/
public LUT[] getLuts() {
ImageProcessor ip2 = getProcessor();
if (ip2==null)
return new LUT[0];
LUT lut = ip2.getLut();
if (lut==null)
return new LUT[0];
LUT[] luts = new LUT[1];
luts[0] = lut;
return luts;
}
/** Calls draw to draw the image and also repaints the
image window to force the information displayed above
the image (dimension, type, size) to be updated. */
public void repaintWindow() {
if (win!=null) {
draw();
win.repaint();
}
}
/** Calls updateAndDraw to update from the pixel data
and draw the image, and also repaints the image
window to force the information displayed above
the image (dimension, type, size) to be updated. */
public void updateAndRepaintWindow() {
if (win!=null) {
updateAndDraw();
win.repaint();
}
}
/** ImageCanvas.paint() calls this method when the
ImageProcessor has generated a new image. */
public void updateImage() {
if (ip!=null)
img = ip.createImage();
}
/** Closes the window, if any, that is displaying this image. */
public void hide() {
if (win==null) {
Interpreter.removeBatchModeImage(this);
return;
}
boolean unlocked = lockSilently();
Overlay overlay2 = getOverlay();
changes = false;
win.close();
win = null;
setOverlay(overlay2);
if (unlocked) unlock();
}
/** Closes this image and sets the ImageProcessor to null. To avoid the
"Save changes?" dialog, first set the public 'changes' variable to false. */
public void close() {
ImageWindow win = getWindow();
if (win!=null)
win.close();
else {
if (WindowManager.getCurrentImage()==this)
WindowManager.setTempCurrentImage(null);
deleteRoi(); //save any ROI so it can be restored later
Interpreter.removeBatchModeImage(this);
}
}
/** Opens a window to display this image and clears the status bar. */
public void show() {
show("");
}
/** Opens a window to display this image and displays
'statusMessage' in the status bar. */
public void show(String statusMessage) {
if (isVisible())
return;
win = null;
if ((IJ.isMacro() && ij==null) || Interpreter.isBatchMode()) {
if (isComposite()) ((CompositeImage)this).reset();
ImagePlus imp = WindowManager.getCurrentImage();
if (imp!=null) imp.saveRoi();
WindowManager.setTempCurrentImage(this);
Interpreter.addBatchModeImage(this);
return;
}
if (Prefs.useInvertingLut && getBitDepth()==8 && ip!=null && !ip.isInvertedLut()&& !ip.isColorLut())
invertLookupTable();
img = getImage();
if ((img!=null) && (width>=0) && (height>=0)) {
activated = false;
int stackSize = getStackSize();
if (stackSize>1)
win = new StackWindow(this);
else if (getProperty(Plot.PROPERTY_KEY) != null)
win = new PlotWindow(this, (Plot)(getProperty(Plot.PROPERTY_KEY)));
else
win = new ImageWindow(this);
if (roi!=null) roi.setImage(this);
if (overlay!=null && getCanvas()!=null)
getCanvas().setOverlay(overlay);
IJ.showStatus(statusMessage);
if (IJ.isMacro()) { // wait for window to be activated
long start = System.currentTimeMillis();
while (!activated) {
IJ.wait(5);
if ((System.currentTimeMillis()-start)>2000) {
WindowManager.setTempCurrentImage(this);
break; // 2 second timeout
}
}
}
if (imageType==GRAY16 && default16bitDisplayRange!=0) {
resetDisplayRange();
updateAndDraw();
}
if (stackSize>1) {
int c = getChannel();
int z = getSlice();
int t = getFrame();
if (c>1 || z>1 || t>1)
setPosition(c, z, t);
}
if (setIJMenuBar)
IJ.wait(25);
notifyListeners(OPENED);
}
}
void invertLookupTable() {
int nImages = getStackSize();
ip.invertLut();
if (nImages==1)
ip.invert();
else {
ImageStack stack2 = getStack();
for (int i=1; i<=nImages; i++)
stack2.getProcessor(i).invert();
stack2.setColorModel(ip.getColorModel());
}
}
/** Called by ImageWindow.windowActivated(). */
public void setActivated() {
activated = true;
}
/** Returns this image as a AWT image. */
public Image getImage() {
if (img==null && ip!=null)
img = ip.createImage();
return img;
}
/** Returns a copy of this image as an 8-bit or RGB BufferedImage.
* @see ij.process.ShortProcessor#get16BitBufferedImage
*/
public BufferedImage getBufferedImage() {
if (isComposite())
return (new ColorProcessor(getImage())).getBufferedImage();
else
return ip.getBufferedImage();
}
/** Returns this image's unique numeric ID. */
public int getID() {
return ID;
}
/** Replaces the image, if any, with the one specified.
Throws an IllegalStateException if an error occurs
while loading the image. */
public void setImage(Image image) {
if (image instanceof BufferedImage) {
BufferedImage bi = (BufferedImage)image;
if (bi.getType()==BufferedImage.TYPE_USHORT_GRAY) {
setProcessor(null, new ShortProcessor(bi));
return;
} else if (bi.getType()==BufferedImage.TYPE_BYTE_GRAY) {
setProcessor(null, new ByteProcessor(bi));
return;
}
}
roi = null;
errorLoadingImage = false;
waitForImage(image);
if (errorLoadingImage)
throw new IllegalStateException ("Error loading image");
int newWidth = image.getWidth(ij);
int newHeight = image.getHeight(ij);
boolean dimensionsChanged = newWidth!=width || newHeight!=height;
width = newWidth;
height = newHeight;
setStackNull();
LookUpTable lut = new LookUpTable(image);
int type = lut.getMapSize()>0?GRAY8:COLOR_RGB;
if (image!=null && type==COLOR_RGB)
ip = new ColorProcessor(image);
if (ip==null && image!=null)
ip = new ByteProcessor(image);
setType(type);
this.img = ip.createImage();
if (win!=null) {
if (dimensionsChanged)
win = new ImageWindow(this);
else
repaintWindow();
}
}
/** Replaces this image with the specified ImagePlus. May
not work as expected if 'imp' is a CompositeImage
and this image is not. */
public void setImage(ImagePlus imp) {
Properties newProperties = imp.getProperties();
if (newProperties!=null)
newProperties = (Properties)(newProperties.clone());
if (imp.getWindow()!=null)
imp = imp.duplicate();
ImageStack stack2 = imp.getStack();
if (imp.isHyperStack())
setOpenAsHyperStack(true);
LUT[] luts = null;
if (imp.isComposite() && (this instanceof CompositeImage)) {
if (((CompositeImage)imp).getMode()!=((CompositeImage)this).getMode())
((CompositeImage)this).setMode(((CompositeImage)imp).getMode());
luts = ((CompositeImage)imp).getLuts();
}
LUT lut = !imp.isComposite()?imp.getProcessor().getLut():null;
setStack(stack2, imp.getNChannels(), imp.getNSlices(), imp.getNFrames());
compositeImage = imp.isComposite();
if (luts!=null) {
((CompositeImage)this).setLuts(luts);
((CompositeImage)this).setMode(((CompositeImage)imp).getMode());
updateAndRepaintWindow();
} else if (lut!=null) {
getProcessor().setLut(lut);
updateAndRepaintWindow();
}
setTitle(imp.getTitle());
setCalibration(imp.getCalibration());
setOverlay(imp.getOverlay());
properties = newProperties;
if (getProperty(Plot.PROPERTY_KEY)!=null && win instanceof PlotWindow) {
Plot plot = (Plot)(getProperty(Plot.PROPERTY_KEY));
((PlotWindow)win).setPlot(plot);
plot.setImagePlus(this);
}
setFileInfo(imp.getOriginalFileInfo());
setProperty ("Info", imp.getProperty ("Info"));
}
/** Replaces the ImageProcessor with the one specified and updates the
display. With stacks, the ImageProcessor must be the same type as the
other images in the stack and it must be the same width and height. */
public void setProcessor(ImageProcessor ip) {
setProcessor(null, ip);
}
/** Replaces the ImageProcessor with the one specified and updates the display. With
stacks, the ImageProcessor must be the same type as other images in the stack and
it must be the same width and height. Set 'title' to null to leave the title unchanged. */
public void setProcessor(String title, ImageProcessor ip) {
if (ip==null || ip.getPixels()==null)
throw new IllegalArgumentException("ip null or ip.getPixels() null");
if (getStackSize()>1) {
if (ip.getWidth()!=width || ip.getHeight()!=height)
throw new IllegalArgumentException("Wrong dimensions for this stack");
int stackBitDepth = stack!=null?stack.getBitDepth():0;
if (stackBitDepth>0 && getBitDepth()!=stackBitDepth)
throw new IllegalArgumentException("Wrong type for this stack");
} else {
setStackNull();
setCurrentSlice(1);
}
setProcessor2(title, ip, null);
}
void setProcessor2(String title, ImageProcessor ip, ImageStack newStack) {
//IJ.log("setProcessor2: "+ip+" "+this.ip+" "+newStack);
if (title!=null) setTitle(title);
if (ip==null)
return;
this.ip = ip;
if (this.ip!=null && getWindow()!=null)
notifyListeners(UPDATED);
if (ij!=null)
ip.setProgressBar(ij.getProgressBar());
int stackSize = 1;
boolean dimensionsChanged = width>0 && height>0 && (width!=ip.getWidth() || height!=ip.getHeight());
if (stack!=null) {
stackSize = stack.size();
if (currentSlice>stackSize)
setCurrentSlice(stackSize);
if (currentSlice>=1 && currentSlice<=stackSize && !dimensionsChanged)
stack.setPixels(ip.getPixels(),currentSlice);
}
img = null;
if (dimensionsChanged) roi = null;
int type;
if (ip instanceof ByteProcessor)
type = GRAY8;
else if (ip instanceof ColorProcessor)
type = COLOR_RGB;
else if (ip instanceof ShortProcessor)
type = GRAY16;
else
type = GRAY32;
if (width==0)
imageType = type;
else
setType(type);
width = ip.getWidth();
height = ip.getHeight();
if (win!=null) {
if (dimensionsChanged && stackSize==1)
win.updateImage(this);
else if (newStack==null)
repaintWindow();
draw();
}
}
/** Replaces the image with the specified stack and updates the display. */
public void setStack(ImageStack stack) {
setStack(null, stack);
}
/** Replaces the image with the specified stack and updates
the display. Set 'title' to null to leave the title unchanged. */
public void setStack(String title, ImageStack newStack) {
//IJ.log("setStack1: "+nChannels+" "+nSlices+" "+nFrames);
int bitDepth1 = getBitDepth();
int previousStackSize = getStackSize();
int newStackSize = newStack.getSize();
if (newStackSize==0)
throw new IllegalArgumentException("Stack is empty");
if (!newStack.isVirtual()) {
Object[] arrays = newStack.getImageArray();
if (arrays==null || (arrays.length>0&&arrays[0]==null))
throw new IllegalArgumentException("Stack pixel array null");
}
boolean sliderChange = false;
if (win!=null && (win instanceof StackWindow)) {
int nScrollbars = ((StackWindow)win).getNScrollbars();
if (nScrollbars>0 && newStackSize==1)
sliderChange = true;
else if (nScrollbars==0 && newStackSize>1)
sliderChange = true;
}
if (currentSlice<1) setCurrentSlice(1);
boolean resetCurrentSlice = currentSlice>newStackSize;
if (resetCurrentSlice) setCurrentSlice(newStackSize);
ImageProcessor ip = newStack.getProcessor(currentSlice);
boolean dimensionsChanged = width>0 && height>0 && (width!=ip.getWidth()||height!=ip.getHeight());
if (this.stack==null)
newStack.viewers(+1);
this.stack = newStack;
oneSliceStack = false;
setProcessor2(title, ip, newStack);
if (bitDepth1!=0 && bitDepth1!=getBitDepth())
compositeChanges = true;
if (compositeChanges && (this instanceof CompositeImage)) {
this.compositeImage = getStackSize()!=getNSlices();
((CompositeImage)this).completeReset();
if (bitDepth1!=0 && bitDepth1!=getBitDepth())
((CompositeImage)this).resetDisplayRanges();
}
compositeChanges = false;
if (win==null) {
if (resetCurrentSlice) setSlice(currentSlice);
return;
}
boolean invalidDimensions = (isDisplayedHyperStack()||(this instanceof CompositeImage)) && (win instanceof StackWindow) && !((StackWindow)win).validDimensions();
if (newStackSize>1 && !(win instanceof StackWindow)) {
if (isDisplayedHyperStack())
setOpenAsHyperStack(true);
activated = false;
win = new StackWindow(this, dimensionsChanged?null:getCanvas()); // replaces this window
if (IJ.isMacro()) { // wait for stack window to be activated
long start = System.currentTimeMillis();
while (!activated) {
IJ.wait(5);
if ((System.currentTimeMillis()-start)>200)
break; // 0.2 second timeout
}
}
setPosition(1, 1, 1);
} else if (newStackSize>1 && invalidDimensions) {
if (isDisplayedHyperStack())
setOpenAsHyperStack(true);
win = new StackWindow(this); // replaces this window
setPosition(1, 1, 1);
} else if (dimensionsChanged || sliderChange) {
win.updateImage(this);
} else {
if (win!=null && win instanceof StackWindow)
((StackWindow)win).updateSliceSelector();
if (isComposite()) {
((CompositeImage)this).reset();
updateAndDraw();
}
repaintWindow();
}
if (resetCurrentSlice)
setSlice(currentSlice);
}
public void setStack(ImageStack newStack, int channels, int slices, int frames) {
if (newStack==null || channels*slices*frames!=newStack.getSize())
throw new IllegalArgumentException("channels*slices*frames!=stackSize");
if (IJ.debugMode) IJ.log("setStack: "+newStack.getSize()+" "+channels+" "+slices+" "+frames+" "+isComposite());
compositeChanges = channels!=this.nChannels;
this.nChannels = channels;
this.nSlices = slices;
this.nFrames = frames;
setStack(null, newStack);
}
private synchronized void setStackNull() {
if (oneSliceStack && stack!=null && stack.size()>0) {
String label = stack.getSliceLabel(1);
setProperty("Label", label);
}
stack = null;
oneSliceStack = false;
}
/** Saves this image's FileInfo so it can be later
retieved using getOriginalFileInfo(). */
public void setFileInfo(FileInfo fi) {
if (fi!=null)
fi.pixels = null;
fileInfo = fi;
}
/** Returns the ImageWindow that is being used to display
this image. Returns null if show() has not be called
or the ImageWindow has been closed. */
public ImageWindow getWindow() {
return win;
}
/** Returns true if this image is currently being displayed in a window. */
public boolean isVisible() {
return win!=null && win.isVisible();
}
/** This method should only be called from an ImageWindow. */
public void setWindow(ImageWindow win) {
this.win = win;
if (roi!=null)
roi.setImage(this); // update roi's 'ic' field
}
/** Returns the ImageCanvas being used to
display this image, or null. */
public ImageCanvas getCanvas() {
return win!=null?win.getCanvas():flatteningCanvas;
}
/** Sets current foreground color. */
public void setColor(Color c) {
if (ip!=null)
ip.setColor(c);
}
void setupProcessor() {
}
public boolean isProcessor() {
return ip!=null;
}
/** Returns a reference to the current ImageProcessor. If there
is no ImageProcessor, it creates one. Returns null if this
ImagePlus contains no ImageProcessor and no AWT Image.
Sets the line width to the current line width and sets the
calibration table if the image is density calibrated. */
public ImageProcessor getProcessor() {
if (ip==null)
return null;
if (roi!=null && roi.isArea())
ip.setRoi(roi.getBounds());
else
ip.resetRoi();
if (!compositeImage)
ip.setLineWidth(Line.getWidth());
if (ij!=null)
ip.setProgressBar(ij.getProgressBar());
Calibration cal = getCalibration();
if (cal.calibrated())
ip.setCalibrationTable(cal.getCTable());
else
ip.setCalibrationTable(null);
if (Recorder.record) {
Recorder recorder = Recorder.getInstance();
if (recorder!=null) recorder.imageUpdated(this);
}
return ip;
}
/** Frees RAM by setting the snapshot (undo) buffer in
the current ImageProcessor to null. */
public void trimProcessor() {
ImageProcessor ip2 = ip;
if (!locked && ip2!=null) {
if (IJ.debugMode) IJ.log(title + ": trimProcessor");
Roi roi2 = getRoi();
if (roi2!=null && roi2.getPasteMode()!=Roi.NOT_PASTING)
roi2.endPaste();
ip2.setSnapshotPixels(null);
}
}
/** For images with irregular ROIs, returns a byte mask, otherwise, returns
* null. Mask pixels have a non-zero value.and the dimensions of the
* mask are equal to the width and height of the ROI.
* @see ij.ImagePlus#createRoiMask
* @see ij.ImagePlus#createThresholdMask
*/
public ImageProcessor getMask() {
if (roi==null) {
if (ip!=null) ip.resetRoi();
return null;
}
ImageProcessor mask = roi.getMask();
if (mask==null)
return null;
if (ip!=null && roi!=null) {
ip.setMask(mask);
ip.setRoi(roi.getBounds());
}
return mask;
}
/** Returns an 8-bit binary (foreground=255, background=0)
* ROI or overlay mask that has the same dimensions
* as this image. Creates an ROI mask If the image has both
* both an ROI and an overlay. Set the threshold of the mask to 255.
* @see #createThresholdMask
* @see ij.gui.Roi#getMask
*/
public ByteProcessor createRoiMask() {
Roi roi2 = getRoi();
Overlay overlay2 = getOverlay();
if (roi2==null && overlay2==null)
throw new IllegalArgumentException("ROI or overlay required");
ByteProcessor mask = new ByteProcessor(getWidth(),getHeight());
mask.setColor(255);
if (roi2!=null)
mask.fill(roi2);
else if (overlay2!=null) {
if (overlay2.size()==1 && (overlay2.get(0) instanceof ImageRoi)) {
ImageRoi iRoi = (ImageRoi)overlay2.get(0);
ImageProcessor ip = iRoi.getProcessor();
if (ip.getWidth()!=mask.getWidth() || ip.getHeight()!=mask.getHeight())
return mask;
for (int i=0; i<ip.getPixelCount(); i++) {
if (ip.get(i)!=0)
mask.set(i, 255);
}
} else {
for (int i=0; i<overlay2.size(); i++)
mask.fill(overlay2.get(i));
}
}
mask.setThreshold(255, 255, ImageProcessor.NO_LUT_UPDATE);
return mask;
}
/** Returns an 8-bit binary threshold mask
* (foreground=255, background=0)
* that has the same dimensions as this image.
* The threshold of the mask is set to 255.
* @see ij.plugin.Thresholder#createMask
* @see ij.process.ImageProcessor#createMask
*/
public ByteProcessor createThresholdMask() {
ByteProcessor mask = Thresholder.createMask(this);
mask.setThreshold(255, 255, ImageProcessor.NO_LUT_UPDATE);
return mask;
}
/** Get calibrated statistics for this image or ROI, including
histogram, area, mean, min and max, standard
deviation and mode.
This code demonstrates how to get the area, mean
max and median of the current image or selection:
<pre>
imp = IJ.getImage();
stats = imp.getStatistics();
IJ.log("Area: "+stats.area);
IJ.log("Mean: "+stats.mean);
IJ.log("Max: "+stats.max);
</pre>
@return an {@link ij.process.ImageStatistics} object
@see #getAllStatistics
@see #getRawStatistics
@see ij.process.ImageProcessor#getStats
*/
public ImageStatistics getStatistics() {
return getStatistics(AREA+MEAN+STD_DEV+MODE+MIN_MAX+RECT);
}
/** This method returns complete calibrated statistics for this
* image or ROI (with "Limit to threshold"), but it is up to 70 times
* slower than getStatistics().
* @return an {@link ij.process.ImageStatistics} object
* @see #getStatistics
* @see ij.process.ImageProcessor#getStatistics
*/