forked from imagej/ImageJ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPolygonRoi.java
1706 lines (1619 loc) · 52 KB
/
PolygonRoi.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.gui;
import ij.*;
import ij.process.*;
import ij.measure.*;
import ij.plugin.frame.*;
import ij.util.Tools;
import ij.util.FloatArray;
import java.awt.*;
import java.awt.image.*;
import java.awt.geom.*;
import java.awt.event.*;
/** This class represents a polygon region of interest or polyline of interest. */
public class PolygonRoi extends Roi {
protected int maxPoints = 1000; // will be increased if necessary
protected int[] xp, yp; // image coordinates relative to origin of roi bounding box
protected float[] xpf, ypf; // or alternative sub-pixel coordinates
protected int[] xp2, yp2; // absolute screen coordinates
protected int nPoints;
protected float[] xSpline,ySpline; // relative image coordinates
protected int splinePoints = 200;
Rectangle clip;
private double angle1, degrees=Double.NaN;
private int xClipMin, yClipMin, xClipMax, yClipMax;
private boolean userCreated;
private int boxSize = 8;
long mouseUpTime = 0;
/** Creates a new polygon or polyline ROI from x and y coordinate arrays.
Type must be Roi.POLYGON, Roi.FREEROI, Roi.TRACED_ROI, Roi.POLYLINE, Roi.FREELINE or Roi.ANGLE.*/
public PolygonRoi(int[] xPoints, int[] yPoints, int nPoints, int type) {
super(0, 0, null);
init1(nPoints, type);
xp = xPoints;
yp = yPoints;
if (type!=TRACED_ROI) {
xp = new int[nPoints];
yp = new int[nPoints];
for (int i=0; i<nPoints; i++) {
xp[i] = xPoints[i];
yp[i] = yPoints[i];
}
}
xp2 = new int[nPoints];
yp2 = new int[nPoints];
init2(type);
}
/** Creates a new polygon or polyline ROI from float x and y arrays.
Type must be Roi.POLYGON, Roi.FREEROI, Roi.POLYLINE, Roi.FREELINE or Roi.ANGLE.*/
public PolygonRoi(float[] xPoints, float[] yPoints, int nPoints, int type) {
super(0, 0, null);
init1(nPoints, type);
xpf = new float[nPoints];
ypf = new float[nPoints];
for (int i=0; i<nPoints; i++) {
xpf[i] = xPoints[i];
ypf[i] = yPoints[i];
}
enableSubPixelResolution();
xp2 = new int[nPoints];
yp2 = new int[nPoints];
init2(type);
}
/** Creates a new polygon or polyline ROI from float x and y arrays.
Type must be Roi.POLYGON, Roi.FREEROI, Roi.POLYLINE, Roi.FREELINE or Roi.ANGLE.*/
public PolygonRoi(float[] xPoints, float[] yPoints, int type) {
this(xPoints, yPoints, xPoints.length, type);
}
private void init1(int nPoints, int type) throws IllegalArgumentException{
maxPoints = nPoints;
this.nPoints = nPoints;
if (type==POLYGON)
this.type = POLYGON;
else if (type==FREEROI)
this.type = FREEROI;
else if (type==TRACED_ROI)
this.type = TRACED_ROI;
else if (type==POLYLINE)
this.type = POLYLINE;
else if (type==FREELINE)
this.type = FREELINE;
else if (type==ANGLE)
this.type = ANGLE;
else if (type==POINT)
this.type = POINT;
else
throw new IllegalArgumentException("PolygonRoi: Invalid type");
}
private void init2(int type) {
if (type==ANGLE && nPoints==3)
getAngleAsString();
if (type==POINT && Toolbar.getMultiPointMode()) {
Prefs.pointAutoMeasure = false;
Prefs.pointAutoNextSlice = false;
Prefs.pointAddToManager = false;
Prefs.pointAddToOverlay = false;
userCreated = true;
}
if (lineWidth>1 && isLine())
updateWideLine(lineWidth);
finishPolygon();
}
/** Creates a new polygon or polyline ROI from a Polygon. Type must be Roi.POLYGON,
Roi.FREEROI, Roi.TRACED_ROI, Roi.POLYLINE, Roi.FREELINE or Roi.ANGLE.*/
public PolygonRoi(Polygon p, int type) {
this(p.xpoints, p.ypoints, p.npoints, type);
}
/** Creates a new polygon or polyline ROI from a FloatPolygon. Type must be Roi.POLYGON,
Roi.FREEROI, Roi.TRACED_ROI, Roi.POLYLINE, Roi.FREELINE or Roi.ANGLE.*/
public PolygonRoi(FloatPolygon p, int type) {
this(p.xpoints, p.ypoints, p.npoints, type);
}
/** @deprecated */
public PolygonRoi(int[] xPoints, int[] yPoints, int nPoints, ImagePlus imp, int type) {
this(xPoints, yPoints, nPoints, type);
setImage(imp);
}
/** Starts the process of creating a new user-generated polygon or polyline ROI. */
public PolygonRoi(int sx, int sy, ImagePlus imp) {
super(sx, sy, imp);
int tool = Toolbar.getToolId();
switch (tool) {
case Toolbar.POLYGON:
type = POLYGON;
break;
case Toolbar.FREEROI:
type = FREEROI;
break;
case Toolbar.FREELINE:
type = FREELINE;
break;
case Toolbar.ANGLE:
type = ANGLE;
break;
default:
type = POLYLINE;
break;
}
if (magnificationForSubPixel())
enableSubPixelResolution();
previousSX = sx;
previousSY = sy;
x = offScreenX(sx);
y = offScreenY(sy);
startXD = offScreenXD(sx);
startYD = offScreenYD(sy);
if (subPixelResolution()) {
setLocation(startXD, startYD);
xpf = new float[maxPoints];
ypf = new float[maxPoints];
double xbase = getXBase();
double ybase = getYBase();
xpf[0] = (float)(startXD-xbase);
ypf[0] = (float)(startYD-ybase);
xpf[1] = xpf[0];
ypf[1] = ypf[0];
} else {
xp = new int[maxPoints];
yp = new int[maxPoints];
}
xp2 = new int[maxPoints];
yp2 = new int[maxPoints];
nPoints = 2;
width=1;
height=1;
clipX = x;
clipY = y;
clipWidth = 1;
clipHeight = 1;
state = CONSTRUCTING;
userCreated = true;
if (lineWidth>1 && isLine())
updateWideLine(lineWidth);
boxSize = (int)(boxSize*Prefs.getGuiScale());
}
private void drawStartBox(Graphics g) {
if (type!=ANGLE)
g.drawRect(screenXD(startXD)-4, screenYD(startYD)-4, 8, 8);
}
public void draw(Graphics g) {
updatePolygon();
Color color = strokeColor!=null?strokeColor:ROIColor;
boolean hasHandles = xSpline!=null||type==POLYGON||type==POLYLINE||type==ANGLE;
boolean isActiveOverlayRoi = !overlay && isActiveOverlayRoi();
if (isActiveOverlayRoi) {
if (color==Color.cyan)
color = Color.magenta;
else
color = Color.cyan;
}
boolean fill = false;
mag = getMagnification();
if (fillColor!=null && !isLine() && state!=CONSTRUCTING) {
color = fillColor;
fill = true;
}
g.setColor(color);
Graphics2D g2d = (Graphics2D)g;
setRenderingHint(g2d);
if (stroke!=null && !isActiveOverlayRoi)
g2d.setStroke(getScaledStroke());
if (xSpline!=null) {
if (type==POLYLINE || type==FREELINE) {
drawSpline(g, xSpline, ySpline, splinePoints, false, fill, isActiveOverlayRoi);
if (wideLine && !overlay) {
g2d.setStroke(onePixelWide);
g.setColor(getColor());
drawSpline(g, xSpline, ySpline, splinePoints, false, fill, isActiveOverlayRoi);
}
} else
drawSpline(g, xSpline, ySpline, splinePoints, true, fill, isActiveOverlayRoi);
} else {
if (type==POLYLINE || type==FREELINE || type==ANGLE || state==CONSTRUCTING) {
g.drawPolyline(xp2, yp2, nPoints);
if (wideLine && !overlay) {
g2d.setStroke(onePixelWide);
g.setColor(getColor());
g.drawPolyline(xp2, yp2, nPoints);
}
} else {
if (fill) {
if (isActiveOverlayRoi) {
g.setColor(Color.cyan);
g.drawPolygon(xp2, yp2, nPoints);
} else
g.fillPolygon(xp2, yp2, nPoints);
} else
g.drawPolygon(xp2, yp2, nPoints);
}
if (state==CONSTRUCTING && type!=FREEROI && type!=FREELINE)
drawStartBox(g);
}
if (hasHandles && clipboard==null && !overlay) {
if (activeHandle>0)
drawHandle(g, xp2[activeHandle-1], yp2[activeHandle-1]);
if (activeHandle<nPoints-1)
drawHandle(g, xp2[activeHandle+1], yp2[activeHandle+1]);
handleColor= strokeColor!=null? strokeColor:ROIColor; drawHandle(g, xp2[0], yp2[0]); handleColor=Color.white;
for (int i=1; i<nPoints; i++)
drawHandle(g, xp2[i], yp2[i]);
}
drawPreviousRoi(g);
if (!(state==MOVING_HANDLE||state==CONSTRUCTING||state==NORMAL))
showStatus();
if (updateFullWindow) {
updateFullWindow = false;
imp.draw();
}
}
private void drawSpline(Graphics g, float[] xpoints, float[] ypoints, int npoints, boolean closed, boolean fill, boolean isActiveOverlayRoi) {
if (xpoints==null || xpoints.length==0)
return;
boolean doScaling = (ic != null); //quicker drawing if we don't need to convert to screen coordinates
if (ic!=null) {
Rectangle srcRect = ic.getSrcRect();
if (srcRect.x == 0 && srcRect.y == 0 && ic.getMagnification()==1.0)
doScaling = false;
}
double xd = getXBase();
double yd = getYBase();
Graphics2D g2d = (Graphics2D)g;
GeneralPath path = new GeneralPath();
path.moveTo(screenXD(xpoints[0]+xd), screenYD(ypoints[0]+yd));
if (doScaling) {
for (int i=1; i<npoints; i++)
path.lineTo(screenXD(xpoints[i]+xd), screenYD(ypoints[i]+yd));
} else {
double xd1 = xd, yd1 = yd;
if (useLineSubpixelConvention()) {xd1 += 0.5; yd1 += 0.5;}
for (int i=1; i<npoints; i++)
path.lineTo(xpoints[i]+xd1, ypoints[i]+yd1);
}
if (closed)
path.lineTo(screenXD(xpoints[0]+xd), screenYD(ypoints[0]+yd));
if (fill) {
if (isActiveOverlayRoi) {
g2d.setColor(Color.cyan);
g2d.draw(path);
} else
g2d.fill(path);
} else
g2d.draw(path);
}
public void drawPixels(ImageProcessor ip) {
int saveWidth = ip.getLineWidth();
if (getStrokeWidth()>1f)
ip.setLineWidth((int)Math.round(getStrokeWidth()));
double xbase = getXBase();
double ybase = getYBase();
if (xSpline!=null) {
ip.moveTo((int)Math.round(xbase+xSpline[0]), (int)Math.round(ybase+ySpline[0]));
for (int i=1; i<splinePoints; i++)
ip.lineTo((int)Math.round(xbase+xSpline[i]), (int)Math.round(ybase+ySpline[i]));
if (type==POLYGON || type==FREEROI || type==TRACED_ROI) // close the shape
ip.lineTo((int)Math.round(xbase+xSpline[0]), (int)Math.round(ybase+ySpline[0]));
} else if (xpf!=null) {
ip.moveTo((int)Math.round(xbase+xpf[0]), (int)Math.round(ybase+ypf[0]));
for (int i=1; i<nPoints; i++)
ip.lineTo((int)Math.round(xbase+xpf[i]), (int)Math.round(ybase+ypf[i]));
if (type==POLYGON || type==FREEROI || type==TRACED_ROI) // close the shape
ip.lineTo((int)Math.round(xbase+xpf[0]), (int)Math.round(ybase+ypf[0]));
} else {
ip.moveTo(x+xp[0], y+yp[0]);
for (int i=1; i<nPoints; i++)
ip.lineTo(x+xp[i], y+yp[i]);
if (type==POLYGON || type==FREEROI || type==TRACED_ROI) // close the shape
ip.lineTo(x+xp[0], y+yp[0]);
}
ip.setLineWidth(saveWidth);
updateFullWindow = true;
}
protected void grow(int sx, int sy) {
// Overrides grow() in Roi class
}
protected void updatePolygon() {
int basex=0, basey=0;
if (ic!=null) {
Rectangle srcRect = ic.getSrcRect();
basex=srcRect.x; basey=srcRect.y;
}
double mag = getMagnification();
if (mag==1.0 && basex==0 && basey==0) {
if (xpf!=null) {
float xbase = (float)getXBase();
float ybase = (float)getYBase();
for (int i=0; i<nPoints; i++) {
xp2[i] = (int)Math.round(xpf[i]+xbase);
yp2[i] = (int)Math.round(ypf[i]+ybase);
}
} else {
for (int i=0; i<nPoints; i++) {
xp2[i] = xp[i]+x;
yp2[i] = yp[i]+y;
}
}
} else {
if (xpf!=null) {
float xbase = (float)getXBase();
float ybase = (float)getYBase();
for (int i=0; i<nPoints; i++) {
xp2[i] = screenXD(xpf[i]+xbase);
yp2[i] = screenYD(ypf[i]+ybase);
}
} else {
for (int i=0; i<nPoints; i++) {
xp2[i] = screenXD(xp[i]+x);
yp2[i] = screenYD(yp[i]+y);
}
}
}
}
public void mouseMoved(MouseEvent e) {
int sx = e.getX();
int sy = e.getY();
int flags = e.getModifiers();
constrain = (flags&Event.SHIFT_MASK)!=0;
if (constrain) { // constrain in 90deg steps
int dx = sx - previousSX;
int dy = sy - previousSY;
if (Math.abs(dx) > Math.abs(dy))
dy = 0;
else
dx = 0;
sx = previousSX + dx;
sy = previousSY + dy;
}
// Do rubber banding
int tool = Toolbar.getToolId();
if (!(tool==Toolbar.POLYGON || tool==Toolbar.POLYLINE || tool==Toolbar.ANGLE)) {
imp.deleteRoi();
imp.draw();
return;
}
if (IJ.altKeyDown())
wipeBack();
drawRubberBand(sx, sy);
// show status: length & angle
degrees = Double.NaN;
double len = -1;
if (nPoints>1) {
double x1, y1, x2, y2;
if (xpf!=null) {
x1 = xpf[nPoints-2];
y1 = ypf[nPoints-2];
x2 = xpf[nPoints-1];
y2 = ypf[nPoints-1];
} else {
x1 = xp[nPoints-2];
y1 = yp[nPoints-2];
x2 = xp[nPoints-1];
y2 = yp[nPoints-1];
}
degrees = getFloatAngle(x1, y1, x2, y2);
if (tool!=Toolbar.ANGLE) {
Calibration cal = imp.getCalibration();
double pw=cal.pixelWidth, ph=cal.pixelHeight;
if (IJ.altKeyDown()) {pw=1.0; ph=1.0;}
len = Math.sqrt((x2-x1)*pw*(x2-x1)*pw + (y2-y1)*ph*(y2-y1)*ph);
}
}
if (tool==Toolbar.ANGLE) {
if (nPoints==2)
angle1 = degrees;
else if (nPoints==3) {
double angle2 = xpf != null ? getFloatAngle(xpf[1], ypf[1], xpf[2], ypf[2]) :
getAngle(xp[1], yp[1], xp[2], yp[2]);
degrees = Math.abs(180-Math.abs(angle1-angle2));
if (degrees>180.0)
degrees = 360.0-degrees;
}
}
String length = len!=-1?", length=" + IJ.d2s(len):"";
double degrees2 = tool==Toolbar.ANGLE&&nPoints==3&&Prefs.reflexAngle?360.0-degrees:degrees;
String angle = !Double.isNaN(degrees)?", angle=" + IJ.d2s(degrees2):"";
int ox = ic.offScreenX(sx);
int oy = ic.offScreenY(sy);
IJ.showStatus(imp.getLocationAsString(ox,oy) + length + angle);
}
//Mouse behaves like an eraser when moved backwards with alt key down.
//Within correction circle, all vertices with sharp angles are removed.
//Norbert Vischer
protected void wipeBack() {
Roi prevRoi = Roi.getPreviousRoi();
if (prevRoi!=null && prevRoi.modState==SUBTRACT_FROM_ROI)
return;
double correctionRadius = 20;
if (ic!=null)
correctionRadius /= ic.getMagnification();
boolean found = false;
int p3 = nPoints - 1;
int p1 = p3;
while (p1 > 0 && !found) {
p1--;
double dx = xpf != null ? xpf[p3] - xpf[p1] : xp[p3] - xp[p1];
double dy = xpf != null ? ypf[p3] - ypf[p1] : yp[p3] - yp[p1];
double dist = Math.sqrt(dx * dx + dy * dy);
if (dist > correctionRadius)
found = true;
}
//examine all angles p1-p2-p3
boolean killed = false;
int safety = 10; //don't delete more than this number of points at once
do {
killed = false;
safety--;
for (int p2 = p1 + 1; p2 < p3; p2++) {
double dx1 = xpf != null ? xpf[p2] - xpf[p1] : xp[p2] - xp[p1];
double dy1 = xpf != null ? ypf[p2] - ypf[p1] : yp[p2] - yp[p1];
double dx2 = xpf != null ? xpf[p3] - xpf[p1] : xp[p3] - xp[p1];
double dy2 = xpf != null ? ypf[p3] - ypf[p1] : yp[p3] - yp[p1];
double kk = 1;//allowed sharpness
if (this instanceof FreehandRoi)
kk = 0.8;
if ((dx1 * dx1 + dy1 * dy1) > kk * (dx2 * dx2 + dy2 * dy2)) {
if (xpf != null) {
xpf[p2] = xpf[p3]; ypf[p2] = ypf[p3]; //replace sharp vertex with end point
} else {
xp[p2] = xp[p3]; yp[p2] = yp[p3];
}
p3 = p2;
nPoints = p2 + 1; //shorten array
killed = true;
}
}
} while (killed && safety > 0);
}
void drawRubberBand(int sx, int sy) {
double oxd = offScreenXD(sx);
double oyd = offScreenYD(sy);
int ox = offScreenX(sx);
int oy = offScreenY(sy);
int x1, y1, x2, y2;
if (xpf!=null) {
x1 = (int)xpf[nPoints-2]+x;
y1 = (int)ypf[nPoints-2]+y;
x2 = (int)xpf[nPoints-1]+x;
y2 = (int)ypf[nPoints-1]+y;
} else {
x1 = xp[nPoints-2]+x;
y1 = yp[nPoints-2]+y;
x2 = xp[nPoints-1]+x;
y2 = yp[nPoints-1]+y;
}
int xmin=Integer.MAX_VALUE, ymin=Integer.MAX_VALUE, xmax=0, ymax=0;
if (x1<xmin) xmin=x1;
if (x2<xmin) xmin=x2;
if (ox<xmin) xmin=ox;
if (x1>xmax) xmax=x1;
if (x2>xmax) xmax=x2;
if (ox>xmax) xmax=ox;
if (y1<ymin) ymin=y1;
if (y2<ymin) ymin=y2;
if (oy<ymin) ymin=oy;
if (y1>ymax) ymax=y1;
if (y2>ymax) ymax=y2;
if (oy>ymax) ymax=oy;
int margin = boxSize;
if (ic!=null) {
double mag = ic.getMagnification();
if (mag<1.0) margin = (int)(margin/mag);
}
margin = (int)(margin+getStrokeWidth());
if (IJ.altKeyDown())
margin+=20;
if (xpf!=null) {
xpf[nPoints-1] = (float)(oxd-getXBase());
ypf[nPoints-1] = (float)(oyd-getYBase());
} else {
xp[nPoints-1] = ox-x;
yp[nPoints-1] = oy-y;
}
if (type==POLYLINE && Prefs.splineFitLines) {
fitSpline();
imp.draw();
} else
imp.draw(xmin-margin, ymin-margin, (xmax-xmin)+margin*2, (ymax-ymin)+margin*2);
}
void finishPolygon() {
if (xpf!=null) {
double xbase0 = getXBase();
double ybase0 = getYBase();
FloatPolygon poly = new FloatPolygon(xpf, ypf, nPoints);
bounds = poly.getFloatBounds();
for (int i=0; i<nPoints; i++) { //xpf, ypf have lowest value of 0.0 sharp
xpf[i] -= (float)bounds.x; //(bounds.x, bounds.y will be adjusted accordingly)
ypf[i] -= (float)bounds.y;
}
if (xSpline!=null) {
for (int i=0; i<splinePoints; i++) {
xSpline[i] += (float)(xbase0 - bounds.x);
ySpline[i] += (float)(ybase0 - bounds.y);
}
}
x = (int)bounds.x; //all points must be within the integer bounding rectangle
y = (int)bounds.y;
width = (int)Math.ceil(bounds.x + bounds.width) - x;
height = (int)Math.ceil(bounds.y + bounds.height) - y;
} else {
Polygon poly = new Polygon(xp, yp, nPoints);
Rectangle r = poly.getBounds();
x = r.x;
y = r.y;
width = r.width;
height = r.height;
for (int i=0; i<nPoints; i++) {
xp[i] = xp[i]-x;
yp[i] = yp[i]-y;
}
bounds = null;
}
if (nPoints<2 || (!(type==FREELINE||type==POLYLINE||type==ANGLE) && (nPoints<3||width==0||height==0))) {
if (imp!=null) imp.deleteRoi();
if (type!=POINT) return;
}
state = NORMAL;
if (imp!=null && !(type==TRACED_ROI))
imp.draw(x-5, y-5, width+10, height+10);
oldX=x; oldY=y; oldWidth=width; oldHeight=height;
if (Recorder.record && userCreated && (type==POLYGON||type==POLYLINE||type==ANGLE
||(type==POINT&&Recorder.scriptMode()&&nPoints==3)))
Recorder.recordRoi(getPolygon(), type);
if (type!=POINT) modifyRoi();
LineWidthAdjuster.update();
notifyListeners(RoiListener.COMPLETED);
updateFullWindow = true;
}
public void exitConstructingMode() {
if (type==POLYLINE && state==CONSTRUCTING) {
addOffset();
finishPolygon();
}
}
protected void moveHandle(int sx, int sy) {
if (constrain) { // constrain in 90deg steps
int dx = sx - previousSX;
int dy = sy - previousSY;
if (Math.abs(dx) > Math.abs(dy))
dy = 0;
else
dx = 0;
sx = previousSX + dx;
sy = previousSY + dy;
}
if (clipboard!=null) return;
int ox = offScreenX(sx);
int oy = offScreenY(sy);
if (xpf!=null) {
xpf[activeHandle] = (float)(offScreenXD(sx)-getXBase());
ypf[activeHandle] = (float)(offScreenYD(sy)-getYBase());
} else {
xp[activeHandle] = ox-x;
yp[activeHandle] = oy-y;
}
if (xSpline!=null) {
fitSpline(splinePoints);
imp.draw();
} else {
if (!subPixelResolution() || (type==POINT&&nPoints==1))
resetBoundingRect();
if (type==POINT && width==0 && height==0)
{width=1; height=1;}
updateClipRectAndDraw();
}
String angle = type==ANGLE?getAngleAsString():"";
IJ.showStatus(imp.getLocationAsString(ox,oy) + angle);
}
/** After handle is moved, find clip rect and repaint. */
void updateClipRectAndDraw() {
if (xpf!=null) {
xp = toInt(xpf, xp, nPoints);
yp = toInt(ypf, yp, nPoints);
}
int xmin=Integer.MAX_VALUE, ymin=Integer.MAX_VALUE, xmax=0, ymax=0;
int x2, y2;
if (activeHandle>0)
{x2=x+xp[activeHandle-1]; y2=y+yp[activeHandle-1];}
else
{x2=x+xp[nPoints-1]; y2=y+yp[nPoints-1];}
if (x2<xmin) xmin = x2;
if (y2<ymin) ymin = y2;
if (x2>xmax) xmax = x2;
if (y2>ymax) ymax = y2;
x2=x+xp[activeHandle]; y2=y+yp[activeHandle];
if (x2<xmin) xmin = x2;
if (y2<ymin) ymin = y2;
if (x2>xmax) xmax = x2;
if (y2>ymax) ymax = y2;
if (activeHandle<nPoints-1)
{x2=x+xp[activeHandle+1]; y2=y+yp[activeHandle+1];}
else
{x2=x+xp[0]; y2=y+yp[0];}
if (x2<xmin) xmin = x2;
if (y2<ymin) ymin = y2;
if (x2>xmax) xmax = x2;
if (y2>ymax) ymax = y2;
int xmin2=xmin, ymin2=ymin, xmax2=xmax, ymax2=ymax;
if (xClipMin<xmin2) xmin2 = xClipMin;
if (yClipMin<ymin2) ymin2 = yClipMin;
if (xClipMax>xmax2) xmax2 = xClipMax;
if (yClipMax>ymax2) ymax2 = yClipMax;
xClipMin=xmin; yClipMin=ymin; xClipMax=xmax; yClipMax=ymax;
double mag = ic.getMagnification();
int handleSize = type==POINT?getHandleSize()+25:getHandleSize();
double strokeWidth = getStrokeWidth();
if (strokeWidth<1.0) strokeWidth=1.0;
if (handleSize<strokeWidth && isLine())
handleSize = (int)strokeWidth;
int m = mag<1.0?(int)(handleSize/mag):handleSize;
m = (int)(m*strokeWidth);
imp.draw(xmin2-m, ymin2-m, xmax2-xmin2+m*2, ymax2-ymin2+m*2);
}
protected void resetBoundingRect() {
//IJ.log("resetBoundingRect");
if (xpf!=null) {
resetSubPixelBoundingRect();
xp = toInt(xpf, xp, nPoints);
yp = toInt(ypf, yp, nPoints);
return;
}
int xmin=Integer.MAX_VALUE, xmax=-xmin, ymin=xmin, ymax=xmax;
int xx, yy;
for (int i=0; i<nPoints; i++) {
xx = xp[i];
if (xx<xmin) xmin=xx;
if (xx>xmax) xmax=xx;
yy = yp[i];
if (yy<ymin) ymin=yy;
if (yy>ymax) ymax=yy;
}
if (xmin!=0) {
for (int i=0; i<nPoints; i++)
xp[i] -= xmin;
}
if (ymin!=0) {
for (int i=0; i<nPoints; i++)
yp[i] -= ymin;
}
//IJ.log("reset: "+ymin+" "+before+" "+yp[0]);
x+=xmin; y+=ymin;
width=xmax-xmin; height=ymax-ymin;
bounds = null;
}
private void resetSubPixelBoundingRect() {
//IJ.log("resetSubPixelBoundingRect: "+state+" "+bounds);
if (xSpline!=null) {
resetSplineFitBoundingRect();
return;
}
float xbase = (float)getXBase();
float ybase = (float)getYBase();
for (int i=0; i<nPoints; i++) {
xpf[i] = xpf[i]+xbase;
ypf[i] = ypf[i]+ybase;
}
FloatPolygon poly = new FloatPolygon(xpf, ypf, nPoints);
Rectangle r = poly.getBounds();
x = r.x;
y = r.y;
width = r.width;
height = r.height;
bounds = poly.getFloatBounds();
xbase = (float)bounds.x;
ybase = (float)bounds.y;
for (int i=0; i<nPoints; i++) {
xpf[i] -= xbase;
ypf[i] -= ybase;
}
}
private void resetSplineFitBoundingRect() {
if (splinePoints==0)
return;
float xbase = (float)getXBase();
float ybase = (float)getYBase();
float xSpline0 = xSpline[0];
float ySpline0 = ySpline[0];
for (int i=0; i<splinePoints; i++) {
xSpline[i] = xSpline[i]+xbase;
ySpline[i] = ySpline[i]+ybase;
}
FloatPolygon poly = new FloatPolygon(xSpline, ySpline, splinePoints);
Rectangle r = poly.getBounds();
x = r.x;;
y = r.y;
width = r.width;
height = r.height;
bounds = poly.getFloatBounds();
xbase = (float)bounds.x;
ybase = (float)bounds.y;
for (int i=0; i<splinePoints; i++) {
xSpline[i] -= xbase;
ySpline[i] -= ybase;
}
for (int i=0; i<nPoints; i++) {
xpf[i] -= xSpline0 - xSpline[0];
ypf[i] -= ySpline0 - ySpline[0];
}
}
String getAngleAsString() {
double angle1 = 0.0;
double angle2 = 0.0;
if (xpf!=null) {
angle1 = getFloatAngle(xpf[0], ypf[0], xpf[1], ypf[1]);
angle2 = getFloatAngle(xpf[1], ypf[1], xpf[2], ypf[2]);
} else {
angle1 = getFloatAngle(xp[0], yp[0], xp[1], yp[1]);
angle2 = getFloatAngle(xp[1], yp[1], xp[2], yp[2]);
}
degrees = Math.abs(180-Math.abs(angle1-angle2));
if (degrees>180.0)
degrees = 360.0-degrees;
double degrees2 = Prefs.reflexAngle&&type==ANGLE?360.0-degrees:degrees;
return ", angle=" + IJ.d2s(degrees2);
}
protected void mouseDownInHandle(int handle, int sx, int sy) {
if (state==CONSTRUCTING)
return;
int ox = offScreenX(sx);
int oy = offScreenY(sy);
double oxd = offScreenXD(sx);
double oyd = offScreenYD(sy);
if ((IJ.altKeyDown()||IJ.controlKeyDown()) && !(nPoints<=3 && type!=POINT) && !(this instanceof RotatedRectRoi)) {
deleteHandle(oxd, oyd);
return;
} else if (IJ.shiftKeyDown() && type!=POINT && !(this instanceof RotatedRectRoi)) {
addHandle(oxd, oyd);
return;
}
super.mouseDownInHandle(handle, sx, sy); //sets state, activeHandle, previousSX&Y
int m = (int)(10.0/ic.getMagnification());
xClipMin=ox-m; yClipMin=oy-m; xClipMax=ox+m; yClipMax=oy+m;
}
public void deleteHandle(double ox, double oy) {
if (imp==null)
return;
if (nPoints<=1) {
imp.deleteRoi();
return;
}
boolean splineFit = xSpline!=null;
if (splineFit)
removeSplineFit();
FloatPolygon points = getFloatPolygon();
int pointToDelete = getClosestPoint(ox, oy, points);
if (pointToDelete>=0) {
deletePoint(pointToDelete);
if (splineFit)
fitSpline(splinePoints);
imp.draw();
}
}
protected void deletePoint(int index) {
if (index<0 || index>=nPoints)
return;
for (int i=index; i<nPoints-1; i++) {
if (xp!=null) {
xp[i] = xp[i+1];
yp[i] = yp[i+1];
}
if (xp2!=null) {
xp2[i] = xp2[i+1];
yp2[i] = yp2[i+1];
}
if (xpf!=null) {
xpf[i] = xpf[i+1];
ypf[i] = ypf[i+1];
}
}
nPoints--;
}
void addHandle(double ox, double oy) {
if (imp==null || type==ANGLE) return;
boolean splineFit = xSpline != null;
xSpline = null;
FloatPolygon points = getFloatPolygon();
int n = points.npoints;
modState = NO_MODS;
Roi prevRoi = Roi.getPreviousRoi();
if (prevRoi!=null) prevRoi.modState = NO_MODS;
int pointToDuplicate = getClosestPoint(ox, oy, points);
if (pointToDuplicate<0)
return;
FloatPolygon points2 = new FloatPolygon();
for (int i2=0; i2<n; i2++) {
if (i2==pointToDuplicate) {
int i1 = i2-1;
if (i1==-1) i1 = isLine()?i2:n-1;
int i3 = i2+1;
if (i3==n) i3 = isLine()?i2:0;
double x1 = points.xpoints[i1] + 2*(points.xpoints[i2] - points.xpoints[i1])/3;
double y1 = points.ypoints[i1] + 2*(points.ypoints[i2] - points.ypoints[i1])/3;
double x2 = points.xpoints[i2] + (points.xpoints[i3] - points.xpoints[i2])/3;
double y2 = points.ypoints[i2] + (points.ypoints[i3] - points.ypoints[i2])/3;
points2.addPoint(x1, y1);
points2.addPoint(x2, y2);
} else
points2.addPoint(points.xpoints[i2], points.ypoints[i2]);
}
if (type==POINT)
imp.setRoi(new PointRoi(points2));
else {
setPolygon(points2);
if (splineFit)
fitSpline(splinePoints);
if (imp!=null) imp.draw();
}
}
private void setPolygon(FloatPolygon p2) {
nPoints = p2.npoints;
if (nPoints>=maxPoints)
enlargeArrays();
float xbase = (float)getXBase();
float ybase = (float)getYBase();
if (xp==null) {
xp = new int[maxPoints];
yp = new int[maxPoints];
}
for (int i=0; i<nPoints; i++) {
xp[i] = (int)(p2.xpoints[i]-x);
yp[i] = (int)(p2.ypoints[i]-y);
if (xpf!=null) {
xpf[i] = p2.xpoints[i] - xbase;
ypf[i] = p2.ypoints[i] - ybase;
}
}
}
protected int getClosestPoint(double x, double y, FloatPolygon points) {
int index = -1;
double distance = Double.MAX_VALUE;
for (int i=0; i<points.npoints; i++) {
double dx = points.xpoints[i] - x;
double dy = points.ypoints[i] - y;
double distance2 = dx*dx+dy*dy;
if (distance2<distance) {
distance = distance2;
index = i;
}
}
return index;
}
/** Fits a spline, which becomes the new shape of this Roi */
public void fitSpline(int evaluationPoints) {
float[][] spline = getSpline(evaluationPoints, xSpline, ySpline);
setSpline(spline[0], spline[1]);
}
/** Sets the spline as a new shape of this Roi */
void setSpline(float[] xSpline, float[] ySpline) {
this.xSpline = xSpline;
this.ySpline = ySpline;
splinePoints = xSpline.length;
cachedMask = null;
// update protected xp and yp arrays for backward compatibility
xp = toInt(xpf, xp, nPoints);
yp = toInt(ypf, yp, nPoints);
if (state==NORMAL)
resetBoundingRect();
}
/** Fits a spline, but leaves the Roi unchanged.
* The arrays supplied (which may be null) are reused if the number of spline
* points remains unchanged.
* @return Arrays of x coordinates and y coordinates */
float[][] getSpline(int evaluationPoints, float[] xSpline, float[] ySpline) {
if (xpf==null) {
xpf = toFloat(xp);
ypf = toFloat(yp);
enableSubPixelResolution();
}
if (xSpline==null || xSpline.length!=evaluationPoints)
xSpline = new float[evaluationPoints];
if (ySpline==null || ySpline.length!=evaluationPoints)
ySpline = new float[evaluationPoints];
int nNodes = isLine() ? nPoints : nPoints+1;
double length = getUncalibratedLength();
float[] nodePositions = new float[nNodes];
float lastNodePosition = 0f; //independent coordinate for x & y-splines,
nodePositions[0] = 0f; //incremented by the sqrt of the distance between points
for (int i=1; i<nPoints; i++) {
float dx = xpf[i] - xpf[i-1];
float dy = ypf[i] - ypf[i-1];
float dLength = (float)Math.sqrt(Math.sqrt(dx*dx+dy*dy));
if (dLength < 0.001f) dLength = 0.001f; //avoid numerical problems with duplicate points
lastNodePosition += dLength;
nodePositions[i] = lastNodePosition;
}
if (!isLine()) { //closed polygon: close the line
float dx = xpf[nPoints-1] - xpf[0];
float dy = ypf[nPoints-1] - ypf[0];
float dLength = (float)Math.sqrt(Math.sqrt(dx*dx+dy*dy));
if (dLength < 0.001f) dLength = 0.001f;
lastNodePosition += dLength;
nodePositions[nNodes-1] = lastNodePosition;
if (xpf.length < nNodes) enlargeArrays(nNodes);
xpf[nNodes-1] = xpf[0];
ypf[nNodes-1] = ypf[0];
}
SplineFitter sfx = new SplineFitter(nodePositions, xpf, nNodes, !isLine());
SplineFitter sfy = new SplineFitter(nodePositions, ypf, nNodes, !isLine());
// Evaluate the splines at all points
double scale = (double)lastNodePosition/(evaluationPoints-1);
for(int i=0; i<evaluationPoints; i++) {
double xvalue = i*scale;
xSpline[i] = (float)sfx.evalSpline(xvalue);
ySpline[i] = (float)sfy.evalSpline(xvalue);
}
return new float[][] {xSpline, ySpline};
}
/** Fits a spline, which becomes the new shape of this Roi */
public void fitSpline() {
double length = getUncalibratedLength();
int evaluationPoints = (int)(length/2.0);
if (ic!=null) {
double mag = ic.getMagnification();
if (mag<1.0)
evaluationPoints *= mag;;
}
if (evaluationPoints<100)