This repository has been archived by the owner on Jan 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 67
/
RoiManager.java
2451 lines (2324 loc) · 70.2 KB
/
RoiManager.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.plugin.frame;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.awt.List;
import java.util.zip.*;
import java.awt.geom.*;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import ij.*;
import ij.process.*;
import ij.gui.*;
import ij.io.*;
import ij.plugin.filter.*;
import ij.plugin.Colors;
import ij.plugin.OverlayLabels;
import ij.util.*;
import ij.macro.*;
import ij.measure.*;
import ij.plugin.OverlayCommands;
/** This plugin implements the Analyze/Tools/ROI Manager command. */
public class RoiManager extends PlugInFrame implements ActionListener, ItemListener, MouseListener, MouseWheelListener, ListSelectionListener {
public static final String LOC_KEY = "manager.loc";
private static final int BUTTONS = 11;
private static final int DRAW=0, FILL=1, LABEL=2;
private static final int SHOW_ALL=0, SHOW_NONE=1, LABELS=2, NO_LABELS=3;
private static final int MENU=0, COMMAND=1;
private static final int IGNORE_POSITION=-999;
private static final int CHANNEL=0, SLICE=1, FRAME=2, SHOW_DIALOG=3;
private static int rows = 15;
private static int lastNonShiftClick = -1;
private static boolean allowMultipleSelections = true;
private static String moreButtonLabel = "More "+'\u00bb';
private Panel panel;
private static Frame instance;
private static int colorIndex = 4;
private JList list;
private DefaultListModel listModel;
private ArrayList rois = new ArrayList();
private boolean canceled;
private boolean macro;
private boolean ignoreInterrupts;
private PopupMenu pm;
private Button moreButton, colorButton;
private Checkbox showAllCheckbox = new Checkbox("Show All", false);
private Checkbox labelsCheckbox = new Checkbox("Labels", false);
private static boolean measureAll = true;
private static boolean onePerSlice = true;
private static boolean restoreCentered;
private int prevID;
private boolean noUpdateMode;
private int defaultLineWidth = 1;
private Color defaultColor;
private boolean firstTime = true;
private int[] selectedIndexes;
private boolean appendResults;
private static ResultsTable mmResults;
private int imageID;
private boolean allowRecording;
private boolean recordShowAll = true;
/** Opens the "ROI Manager" window, or activates it if it is already open.
* @see #getRoiManager
*/
public RoiManager() {
super("ROI Manager");
if (instance!=null) {
WindowManager.toFront(instance);
return;
}
if (IJ.isMacro() && Interpreter.getBatchModeRoiManager()!=null)
return;
instance = this;
list = new JList();
showWindow();
}
/* Constructs an ROIManager without displaying it. */
public RoiManager(boolean b) {
super("ROI Manager");
list = new JList();
listModel = new DefaultListModel();
list.setModel(listModel);
}
void showWindow() {
ImageJ ij = IJ.getInstance();
addKeyListener(ij);
addMouseListener(this);
addMouseWheelListener(this);
WindowManager.addWindow(this);
//setLayout(new FlowLayout(FlowLayout.CENTER,5,5));
setLayout(new BorderLayout());
listModel = new DefaultListModel();
list.setModel(listModel);
list.setPrototypeCellValue("0000-0000-0000 ");
list.addListSelectionListener(this);
list.addKeyListener(ij);
list.addMouseListener(this);
list.addMouseWheelListener(this);
if (IJ.isLinux()) list.setBackground(Color.white);
JScrollPane scrollPane = new JScrollPane(list, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
add("Center", scrollPane);
panel = new Panel();
int nButtons = BUTTONS;
panel.setLayout(new GridLayout(nButtons, 1, 5, 0));
addButton("Add [t]");
addButton("Update");
addButton("Delete");
addButton("Rename...");
addButton("Measure");
addButton("Deselect");
addButton("Properties...");
addButton("Flatten [F]");
addButton(moreButtonLabel);
showAllCheckbox.addItemListener(this);
panel.add(showAllCheckbox);
labelsCheckbox.addItemListener(this);
panel.add(labelsCheckbox);
add("East", panel);
addPopupMenu();
pack();
Dimension size = getSize();
if (size.width>270)
setSize(size.width-40, size.height);
list.remove(0);
Point loc = Prefs.getLocation(LOC_KEY);
if (loc!=null)
setLocation(loc);
else
GUI.center(this);
show();
}
void addButton(String label) {
Button b = new Button(label);
b.addActionListener(this);
b.addKeyListener(IJ.getInstance());
b.addMouseListener(this);
if (label.equals(moreButtonLabel)) moreButton = b;
panel.add(b);
}
void addPopupMenu() {
pm=new PopupMenu();
//addPopupItem("Select All");
addPopupItem("Open...");
addPopupItem("Save...");
addPopupItem("Fill");
addPopupItem("Draw");
addPopupItem("AND");
addPopupItem("OR (Combine)");
addPopupItem("XOR");
addPopupItem("Split");
addPopupItem("Add Particles");
addPopupItem("Multi Measure");
addPopupItem("Multi Plot");
addPopupItem("Sort");
addPopupItem("Specify...");
addPopupItem("Remove Positions...");
addPopupItem("Labels...");
addPopupItem("List");
addPopupItem("Interpolate ROIs");
addPopupItem("Translate...");
addPopupItem("Help");
addPopupItem("Options...");
add(pm);
}
void addPopupItem(String s) {
MenuItem mi=new MenuItem(s);
mi.addActionListener(this);
pm.add(mi);
}
public void actionPerformed(ActionEvent e) {
String label = e.getActionCommand();
if (label==null)
return;
String command = label;
allowRecording = true;
if (command.equals("Add [t]"))
runCommand("add");
else if (command.equals("Update"))
update(true);
else if (command.equals("Delete"))
delete(false);
else if (command.equals("Rename..."))
rename(null);
else if (command.equals("Properties..."))
setProperties(null, -1, null);
else if (command.equals("Flatten [F]"))
flatten();
else if (command.equals("Measure"))
measure(MENU);
else if (command.equals("Open..."))
open(null);
else if (command.equals("Save...")) {
Thread t1 = new Thread(new Runnable() {
public void run() {save();}
});
t1.start();
} else if (command.equals("Fill"))
drawOrFill(FILL);
else if (command.equals("Draw"))
drawOrFill(DRAW);
else if (command.equals("Deselect"))
deselect();
else if (command.equals(moreButtonLabel)) {
Point ploc = panel.getLocation();
Point bloc = moreButton.getLocation();
pm.show(this, ploc.x, bloc.y);
} else if (command.equals("OR (Combine)"))
combine();
else if (command.equals("Split"))
split();
else if (command.equals("AND"))
and();
else if (command.equals("XOR"))
xor();
else if (command.equals("Add Particles"))
addParticles();
else if (command.equals("Multi Measure"))
multiMeasure("");
else if (command.equals("Multi Plot"))
multiPlot();
else if (command.equals("Sort"))
sort();
else if (command.equals("Specify..."))
specify();
else if (command.equals("Remove Positions..."))
removePositions(SHOW_DIALOG);
else if (command.equals("Labels..."))
labels();
else if (command.equals("List"))
listRois();
else if (command.equals("Interpolate ROIs"))
interpolateRois();
else if (command.equals("Translate..."))
translate();
else if (command.equals("Help"))
help();
else if (command.equals("Options..."))
options();
else if (command.equals("\"Show All\" Color..."))
setShowAllColor();
allowRecording = false;
}
private void interpolateRois() {
IJ.runPlugIn("ij.plugin.RoiInterpolator", "");
if (record())
Recorder.record("roiManager", "Interpolate ROIs");
}
public void itemStateChanged(ItemEvent e) {
Object source = e.getSource();
boolean showAllMode = showAllCheckbox.getState();
if (source==showAllCheckbox) {
if (firstTime && okToSet())
labelsCheckbox.setState(true);
showAll(showAllCheckbox.getState()?SHOW_ALL:SHOW_NONE);
if (Recorder.record && recordShowAll) {
if (showAllMode)
Recorder.record("roiManager", "Show All");
else
Recorder.record("roiManager", "Show None");
}
recordShowAll = true;
firstTime = false;
return;
}
if (source==labelsCheckbox) {
if (firstTime && okToSet())
showAllCheckbox.setState(true);
boolean editState = labelsCheckbox.getState();
boolean showAllState = showAllCheckbox.getState();
if (!showAllState && !editState)
showAll(SHOW_NONE);
else {
showAll(editState?LABELS:NO_LABELS);
if (Recorder.record) {
if (editState)
Recorder.record("roiManager", "Show All with labels");
else if (showAllState)
Recorder.record("roiManager", "Show All without labels");
}
if (editState && !showAllState && okToSet()) {
showAllCheckbox.setState(true);
recordShowAll = false;
}
}
firstTime = false;
return;
}
}
private boolean okToSet() {
return !(IJ.isMacOSX()&&IJ.isJava18());
}
void add(boolean shiftKeyDown, boolean altKeyDown) {
if (shiftKeyDown)
addAndDraw(altKeyDown);
else if (altKeyDown)
addRoi(true);
else
addRoi(false);
}
/** Adds the specified ROI. */
public void addRoi(Roi roi) {
addRoi(roi, false, null, -1);
}
boolean addRoi(boolean promptForName) {
return addRoi(null, promptForName, null, IGNORE_POSITION);
}
boolean addRoi(Roi roi, boolean promptForName, Color color, int lineWidth) {
if (listModel==null)
IJ.log("<<Error: Uninitialized RoiManager>>");
ImagePlus imp = roi==null?getImage():WindowManager.getCurrentImage();
if (roi==null) {
if (imp==null)
return false;
roi = imp.getRoi();
if (roi==null) {
error("The active image does not have a selection.");
return false;
}
}
if ((roi instanceof PolygonRoi) && ((PolygonRoi)roi).getNCoordinates()==0)
return false;
if (color==null && roi.getStrokeColor()!=null)
color = roi.getStrokeColor();
else if (color==null && defaultColor!=null)
color = defaultColor;
boolean ignorePosition = false;
if (lineWidth==IGNORE_POSITION) {
ignorePosition = true;
lineWidth = -1;
}
if (lineWidth<0) {
int sw = (int)roi.getStrokeWidth();
lineWidth = sw>1?sw:defaultLineWidth;
}
if (lineWidth>100) lineWidth = 1;
int n = getCount();
int position = imp!=null&&!ignorePosition?roi.getPosition():0;
int saveCurrentSlice = imp!=null?imp.getCurrentSlice():0;
if (position>0 && position!=saveCurrentSlice)
imp.setSliceWithoutUpdate(position);
else
position = 0;
if (n>0 && !IJ.isMacro() && imp!=null) {
// check for duplicate
Roi roi2 = (Roi)rois.get(n-1);
if (roi2!=null) {
String label = (String)listModel.getElementAt(n-1);
int slice2 = getSliceNumber(roi2, label);
if (roi.equals(roi2) && (slice2==-1||slice2==imp.getCurrentSlice()) && imp.getID()==prevID && !Interpreter.isBatchMode()) {
if (position>0)
imp.setSliceWithoutUpdate(saveCurrentSlice);
return false;
}
}
}
prevID = imp!=null?imp.getID():0;
String name = roi.getName();
if (isStandardName(name))
name = null;
String label = name!=null?name:getLabel(imp, roi, -1);
if (promptForName)
label = promptForName(label);
if (label==null) {
if (position>0)
imp.setSliceWithoutUpdate(saveCurrentSlice);
return false;
}
listModel.addElement(label);
roi.setName(label);
Roi roiCopy = (Roi)roi.clone();
setRoiPosition(imp, roiCopy);
if (lineWidth>1)
roiCopy.setStrokeWidth(lineWidth);
if (color!=null)
roiCopy.setStrokeColor(color);
rois.add(roiCopy);
updateShowAll();
if (record())
recordAdd(defaultColor, defaultLineWidth);
if (position>0)
imp.setSliceWithoutUpdate(saveCurrentSlice);
return true;
}
void recordAdd(Color color, int lineWidth) {
if (Recorder.scriptMode())
Recorder.recordCall("rm.addRoi(imp.getRoi());");
else if (color!=null && lineWidth==1)
Recorder.recordString("roiManager(\"Add\", \""+getHex(color)+"\");\n");
else if (lineWidth>1)
Recorder.recordString("roiManager(\"Add\", \""+getHex(color)+"\", "+lineWidth+");\n");
else
Recorder.record("roiManager", "Add");
}
String getHex(Color color) {
if (color==null) color = ImageCanvas.getShowAllColor();
String hex = Integer.toHexString(color.getRGB());
if (hex.length()==8) hex = hex.substring(2);
return hex;
}
/** Adds the specified ROI to the list. The third argument ('n') will
be used to form the first part of the ROI label if it is >= 0. */
public void add(ImagePlus imp, Roi roi, int n) {
if (IJ.debugMode && n<3 && roi!=null) IJ.log("RoiManager.add: "+n+" "+roi.getName());
if (roi==null)
return;
String label = roi.getName();
String label2 = label;
if (label==null)
label = getLabel(imp, roi, n);
else
label = label+"-"+n;
if (label==null)
return;
listModel.addElement(label);
if (label2!=null)
roi.setName(label2);
else
roi.setName(label);
rois.add((Roi)roi.clone());
}
boolean isStandardName(String name) {
if (name==null)
return false;
int len = name.length();
if (len<9 || (len>0&&!Character.isDigit(name.charAt(0))))
return false;
boolean isStandard = false;
if (len>=14 && name.charAt(4)=='-' && name.charAt(9)=='-' )
isStandard = true;
else if (len>=17 && name.charAt(5)=='-' && name.charAt(11)=='-' )
isStandard = true;
else if (len>=9 && name.charAt(4)=='-')
isStandard = true;
else if (len>=11 && name.charAt(5)=='-')
isStandard = true;
return isStandard;
}
String getLabel(ImagePlus imp, Roi roi, int n) {
Rectangle r = roi.getBounds();
int xc = r.x + r.width/2;
int yc = r.y + r.height/2;
if (n>=0)
{xc = yc; yc=n;}
if (xc<0) xc = 0;
if (yc<0) yc = 0;
int digits = 4;
String xs = "" + xc;
if (xs.length()>digits) digits = xs.length();
String ys = "" + yc;
if (ys.length()>digits) digits = ys.length();
if (digits==4 && imp!=null && (imp.getStackSize()>=10000||imp.getHeight()>=10000))
digits = 5;
xs = "000000" + xc;
ys = "000000" + yc;
String label = ys.substring(ys.length()-digits) + "-" + xs.substring(xs.length()-digits);
if (imp!=null && imp.getStackSize()>1) {
int slice = imp.getCurrentSlice();
String zs = "000000" + slice;
label = zs.substring(zs.length()-digits) + "-" + label;
}
return label;
}
void addAndDraw(boolean altKeyDown) {
if (altKeyDown) {
if (!addRoi(true)) return;
} else if (!addRoi(false))
return;
ImagePlus imp = WindowManager.getCurrentImage();
if (imp!=null) {
Undo.setup(Undo.COMPOUND_FILTER, imp);
IJ.run(imp, "Draw", "slice");
Undo.setup(Undo.COMPOUND_FILTER_DONE, imp);
}
if (record()) Recorder.record("roiManager", "Add & Draw");
}
boolean delete(boolean replacing) {
int count = getCount();
if (count==0)
return error("The list is empty.");
int index[] = getSelectedIndexes();
if (index.length==0 || (replacing&&count>1)) {
String msg = "Delete all items on the list?";
if (replacing)
msg = "Replace items on the list?";
canceled = false;
if (!IJ.isMacro() && !macro) {
YesNoCancelDialog d = new YesNoCancelDialog(this, "ROI Manager", msg);
if (d.cancelPressed())
{canceled = true; return false;}
if (!d.yesPressed()) return false;
}
index = getAllIndexes();
}
if (count==index.length && !replacing) {
rois.clear();
listModel.removeAllElements();
} else {
for (int i=count-1; i>=0; i--) {
boolean delete = false;
for (int j=0; j<index.length; j++) {
if (index[j]==i)
delete = true;
}
if (delete) {
rois.remove(i);
listModel.remove(i);
}
}
}
ImagePlus imp = WindowManager.getCurrentImage();
if (count>1 && index.length==1 && imp!=null)
imp.deleteRoi();
updateShowAll();
if (record()) Recorder.record("roiManager", "Delete");
return true;
}
boolean update(boolean clone) {
ImagePlus imp = getImage();
if (imp==null)
return false;
ImageCanvas ic = imp.getCanvas();
boolean showingAll = ic!=null && ic.getShowAllROIs();
Roi roi = imp.getRoi();
if (roi==null) {
error("The active image does not have a selection.");
return false;
}
int index = list.getSelectedIndex();
if (index<0 && !showingAll)
return error("Exactly one item in the list must be selected.");
if (index>=0) {
if (clone) {
String name = (String)listModel.getElementAt(index);
Roi roi2 = (Roi)roi.clone();
setRoiPosition(imp, roi2);
roi.setName(name);
roi2.setName(name);
rois.set(index, roi2);
} else
rois.set(index, roi);
}
if (record()) Recorder.record("roiManager", "Update");
updateShowAll();
return true;
}
boolean rename(String name2) {
int index = list.getSelectedIndex();
if (index<0)
return error("Exactly one item in the list must be selected.");
String name = (String)listModel.getElementAt(index);
if (name2==null)
name2 = promptForName(name);
if (name2==null)
return false;
if (name2.equals(name))
return false;
Roi roi = (Roi)rois.get(index);
roi.setName(name2);
int position = getSliceNumber(name2);
if (position>0 && roi.getCPosition()==0 && roi.getZPosition()==0 && roi.getTPosition()==0)
roi.setPosition(position);
rois.set(index, roi);
listModel.setElementAt(name2, index);
list.setSelectedIndex(index);
if (Prefs.useNamesAsLabels && labelsCheckbox.getState()) {
ImagePlus imp = WindowManager.getCurrentImage();
if (imp!=null) imp.draw();
}
if (record())
Recorder.record("roiManager", "Rename", name2);
return true;
}
String promptForName(String name) {
GenericDialog gd = new GenericDialog("ROI Manager");
gd.addStringField("Rename As:", name, 20);
gd.showDialog();
if (gd.wasCanceled())
return null;
else
return gd.getNextString();
}
boolean restore(ImagePlus imp, int index, boolean setSlice) {
Roi roi = (Roi)rois.get(index);
if (imp==null || roi==null)
return false;
if (setSlice) {
int c = roi.getCPosition();
int z = roi.getZPosition();
int t = roi.getTPosition();
boolean hyperstack = imp.isHyperStack();
//IJ.log("restore: "+hyperstack+" "+c+" "+z+" "+t);
if (hyperstack && (c>0||z>0||t>0))
imp.setPosition(c, z, t);
else {
String label = (String)listModel.getElementAt(index);
int n = getSliceNumber(roi, label);
if (n>=1 && n<=imp.getStackSize()) {
if (hyperstack) {
if (imp.getNSlices()>1 && n<=imp.getNSlices())
imp.setPosition(imp.getC(),n,imp.getT());
else if (imp.getNFrames()>1 && n<=imp.getNFrames())
imp.setPosition(imp.getC(),imp.getZ(),n);
else
imp.setPosition(n);
} else
imp.setSlice(n);
}
}
}
if (showAllCheckbox.getState() && !restoreCentered && !noUpdateMode) {
roi.setImage(null);
imp.setRoi(roi);
return true;
}
Roi roi2 = (Roi)roi.clone();
Rectangle r = roi2.getBounds();
int width= imp.getWidth(), height=imp.getHeight();
if (restoreCentered) {
ImageCanvas ic = imp.getCanvas();
if (ic!=null) {
Rectangle r1 = ic.getSrcRect();
Rectangle r2 = roi2.getBounds();
roi2.setLocation(r1.x+r1.width/2-r2.width/2, r1.y+r1.height/2-r2.height/2);
}
}
if (r.x>=width || r.y>=height || (r.x+r.width)<0 || (r.y+r.height)<0) {
if (roi2.getType()!=Roi.POINT)
roi2.setLocation((width-r.width)/2, (height-r.height)/2);
}
if (noUpdateMode) {
imp.setRoi(roi2, false);
noUpdateMode = false;
} else
imp.setRoi(roi2, true);
return true;
}
private boolean restoreWithoutUpdate(ImagePlus imp, int index) {
noUpdateMode = true;
if (imp==null)
imp = getImage();
return restore(imp, index, false);
}
/** Returns the slice number associated with the specified name,
or -1 if the name does not include a slice number. */
public int getSliceNumber(String label) {
int slice = -1;
if (label.length()>=14 && label.charAt(4)=='-' && label.charAt(9)=='-')
slice = (int)Tools.parseDouble(label.substring(0,4),-1);
else if (label.length()>=17 && label.charAt(5)=='-' && label.charAt(11)=='-')
slice = (int)Tools.parseDouble(label.substring(0,5),-1);
else if (label.length()>=20 && label.charAt(6)=='-' && label.charAt(13)=='-')
slice = (int)Tools.parseDouble(label.substring(0,6),-1);
return slice;
}
/** Returns the slice number associated with the specified ROI or name,
or -1 if the ROI or name does not include a slice number. */
int getSliceNumber(Roi roi, String label) {
int slice = roi!=null?roi.getPosition():-1;
if (slice==0)
slice=-1;
if (slice==-1)
slice = getSliceNumber(label);
return slice;
}
void open(String path) {
Macro.setOptions(null);
String name = null;
if (path==null || path.equals("")) {
OpenDialog od = new OpenDialog("Open Selection(s)...", "");
String directory = od.getDirectory();
name = od.getFileName();
if (name==null)
return;
path = directory + name;
}
if (Recorder.record && !Recorder.scriptMode())
Recorder.record("roiManager", "Open", path);
if (path.endsWith(".zip")) {
openZip(path);
return;
}
Opener o = new Opener();
if (name==null) name = o.getName(path);
Roi roi = o.openRoi(path);
if (roi!=null) {
if (name.endsWith(".roi"))
name = name.substring(0, name.length()-4);
listModel.addElement(name);
rois.add(roi);
}
updateShowAll();
}
// Modified on 2005/11/15 by Ulrik Stervbo to only read .roi files and to not empty the current list
void openZip(String path) {
ZipInputStream in = null;
ByteArrayOutputStream out = null;
int nRois = 0;
try {
in = new ZipInputStream(new FileInputStream(path));
byte[] buf = new byte[1024];
int len;
ZipEntry entry = in.getNextEntry();
while (entry!=null) {
String name = entry.getName();
if (name.endsWith(".roi")) {
out = new ByteArrayOutputStream();
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
out.close();
byte[] bytes = out.toByteArray();
RoiDecoder rd = new RoiDecoder(bytes, name);
Roi roi = rd.getRoi();
if (roi!=null) {
name = name.substring(0, name.length()-4);
listModel.addElement(name);
rois.add(roi);
nRois++;
}
}
entry = in.getNextEntry();
}
in.close();
} catch (IOException e) {
error(e.toString());
} finally {
if (in!=null)
try {in.close();} catch (IOException e) {}
if (out!=null)
try {out.close();} catch (IOException e) {}
}
if(nRois==0)
error("This ZIP archive does not appear to contain \".roi\" files");
updateShowAll();
}
boolean save() {
if (getCount()==0)
return error("The selection list is empty.");
int[] indexes = getIndexes();
if (indexes.length>1)
return saveMultiple(indexes, null);
String name = (String) listModel.getElementAt(indexes[0]);
Macro.setOptions(null);
SaveDialog sd = new SaveDialog("Save Selection...", name, ".roi");
String name2 = sd.getFileName();
if (name2 == null)
return false;
String dir = sd.getDirectory();
Roi roi = (Roi)rois.get(indexes[0]);
if (!name2.endsWith(".roi")) name2 = name2+".roi";
String newName = name2.substring(0, name2.length()-4);
rois.set(indexes[0], roi);
roi.setName(newName);
listModel.setElementAt(newName, indexes[0]);
RoiEncoder re = new RoiEncoder(dir+name2);
try {
re.write(roi);
} catch (IOException e) {
IJ.error("ROI Manager", e.getMessage());
}
if (record()) {
String path = dir+name2;
if (Recorder.scriptMode())
Recorder.recordCall("IJ.saveAs(imp, \"Selection\", \""+path+"\");");
else
Recorder.record("saveAs", "Selection", path);
}
return true;
}
boolean saveMultiple(int[] indexes, String path) {
Macro.setOptions(null);
if (path==null) {
SaveDialog sd = new SaveDialog("Save ROIs...", "RoiSet", ".zip");
String name = sd.getFileName();
if (name == null)
return false;
if (!(name.endsWith(".zip") || name.endsWith(".ZIP")))
name = name + ".zip";
String dir = sd.getDirectory();
path = dir+name;
}
DataOutputStream out = null;
IJ.showStatus("Saving "+indexes.length+" ROIs "+" to "+path);
long t0 = System.currentTimeMillis();
String[] names = new String[listModel.size()];
for (int i=0; i<listModel.size(); i++)
names[i] = (String)listModel.getElementAt(i);
try {
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(path)));
out = new DataOutputStream(new BufferedOutputStream(zos));
RoiEncoder re = new RoiEncoder(out);
for (int i=0; i<indexes.length; i++) {
IJ.showProgress(i, indexes.length);
String label = getUniqueName(names, indexes[i]);
Roi roi = (Roi)rois.get(indexes[i]);
if (IJ.debugMode) IJ.log("saveMultiple: "+i+" "+label+" "+roi);
if (roi==null) continue;
if (!label.endsWith(".roi")) label += ".roi";
zos.putNextEntry(new ZipEntry(label));
re.write(roi);
out.flush();
}
out.close();
} catch (IOException e) {
error(""+e);
return false;
} finally {
if (out!=null)
try {out.close();} catch (IOException e) {}
}
double time = (System.currentTimeMillis()-t0)/1000.0;
IJ.showProgress(1.0);
IJ.showStatus(IJ.d2s(time,3)+" seconds, "+indexes.length+" ROIs, "+path);
if (Recorder.record && !IJ.isMacro())
Recorder.record("roiManager", "Save", path);
return true;
}
String getUniqueName(String[] names, int index) {
String name = names[index];
int n = 1;
int index2 = getIndex(names, index, name);
while (index2!=-1) {
index2 = getIndex(names, index, name);
if (index2!=-1) {
int lastDash = name.lastIndexOf("-");
if (lastDash!=-1 && name.length()-lastDash<5)
name = name.substring(0, lastDash);
name = name+"-"+n;
n++;
}
index2 = getIndex(names, index, name);
}
names[index] = name;
return name;
}
private int getIndex(String[] names, int index, String name) {
int index2 = -1;
for (int i=0; i<names.length; i++) {
if (i!=index && names[i].equals(name))
return i;
}
return index2;
}
private void listRois() {
Roi[] list = getRoisAsArray();
OverlayCommands.listRois(list);
if (record())
Recorder.record("roiManager", "List");
}
boolean measure(int mode) {
ImagePlus imp = getImage();
if (imp==null)
return false;
int[] indexes = getIndexes();
if (indexes.length==0) return false;
boolean allSliceOne = true;
for (int i=0; i<indexes.length; i++) {
Roi roi = (Roi)rois.get(indexes[i]);
String label = (String) listModel.getElementAt(indexes[i]);
if (getSliceNumber(roi,label)>1) allSliceOne=false;
}
int measurements = Analyzer.getMeasurements();
if (imp.getStackSize()>1)
Analyzer.setMeasurements(measurements|Measurements.SLICE);
int currentSlice = imp.getCurrentSlice();
Analyzer.setMeasurements(measurements&(~Measurements.ADD_TO_OVERLAY));
for (int i=0; i<indexes.length; i++) {
if (restore(getImage(), indexes[i], !allSliceOne))
IJ.run("Measure");
else
break;
}
Analyzer.setMeasurements(measurements);
imp.setSlice(currentSlice);
if (indexes.length>1)
IJ.run("Select None");
if (record()) Recorder.record("roiManager", "Measure");
return true;
}
/** This method measures the selected ROIs, or all ROIs if
* none are selected, on all the slices of a stack and returns
* a ResultsTable arranged with one row per slice.
* @see <a href="http://imagej.nih.gov/ij/macros/js/MultiMeasureDemo.js">JavaScript example</a>
*/
public ResultsTable multiMeasure(ImagePlus imp) {
Roi[] rois = getSelectedRoisAsArray();
ResultsTable rt = multiMeasure(imp, rois, false);
imp.deleteRoi();
return rt;
}
/** This method performs measurements for several ROI's in a stack
and arranges the results with one line per slice. By contrast, the
measure() method produces several lines per slice. The results
from multiMeasure() may be easier to import into a spreadsheet
program for plotting or additional analysis. Based on the multi()
method in Bob Dougherty's Multi_Measure plugin
(http://www.optinav.com/Multi-Measure.htm).
*/
boolean multiMeasure(String cmd) {
ImagePlus imp = getImage();
if (imp==null) return false;
int[] indexes = getIndexes();
if (indexes.length==0)
return false;
int measurements = Analyzer.getMeasurements();
int nSlices = imp.getStackSize();
if (cmd!=null)
appendResults = cmd.contains("append")?true:false;
if (IJ.isMacro()) {
if (cmd.startsWith("multi-measure")) {
measureAll = cmd.contains(" measure") && nSlices>1;
onePerSlice = cmd.contains(" one");
appendResults = cmd.contains(" append");
} else {
if (nSlices>1)
measureAll = true;
onePerSlice = true;
}
} else {
GenericDialog gd = new GenericDialog("Multi Measure");
if (nSlices>1)
gd.addCheckbox("Measure all "+nSlices+" slices", measureAll);
gd.addCheckbox("One row per slice", onePerSlice);
gd.addCheckbox("Append results", appendResults);
int columns = getColumnCount(imp, measurements)*indexes.length;
String str = nSlices==1?"this option":"both options";
gd.setInsets(10, 25, 0);
gd.addMessage(
"Enabling "+str+" will result\n"+
"in a table with "+columns+" columns."
);
gd.showDialog();
if (gd.wasCanceled()) return false;
if (nSlices>1)
measureAll = gd.getNextBoolean();
onePerSlice = gd.getNextBoolean();
appendResults = gd.getNextBoolean();
}
if (!measureAll) nSlices = 1;
int currentSlice = imp.getCurrentSlice();
if (!onePerSlice) {
int measurements2 = nSlices>1?measurements|Measurements.SLICE:measurements;
ResultsTable rt = new ResultsTable();
Analyzer analyzer = new Analyzer(imp, measurements2, rt);
for (int slice=1; slice<=nSlices; slice++) {
if (nSlices>1) imp.setSliceWithoutUpdate(slice);
for (int i=0; i<indexes.length; i++) {
if (restoreWithoutUpdate(imp, indexes[i]))
analyzer.measure();
else
break;
}