77import org .opencv .core .MatOfPoint2f ;
88import org .opencv .imgproc .Imgproc ;
99import org .opencv .core .Rect ;
10-
10+ import org .opencv .core .Mat ;
11+ import org .opencv .core .MatOfInt ;
1112import org .opencv .core .Point ;
1213
1314import java .awt .Rectangle ;
@@ -17,29 +18,29 @@ public class Contour {
1718 private ArrayList <PVector > points ;
1819 private Point [] inputPoints ;
1920 private double polygonApproximationFactor ;
20- PApplet parent ;
21- Rectangle boundingBox ;
21+ private PApplet parent ;
22+ private Rectangle boundingBox ;
23+ public MatOfPoint pointMat ;
2224
2325 public Contour (PApplet parent , MatOfPoint mat ){
2426 polygonApproximationFactor = mat .size ().height * 0.01 ;
2527 this .parent = parent ;
28+ this .pointMat = mat ;
2629
2730 Rect r = Imgproc .boundingRect (mat );
2831 boundingBox = new Rectangle (r .x , r .y , r .width , r .height );
29-
3032 loadPoints (mat .toArray ());
3133 }
3234
3335 public Contour (PApplet parent , MatOfPoint2f mat ){
3436 polygonApproximationFactor = mat .size ().height * 0.01 ;
3537 this .parent = parent ;
38+ this .pointMat = new MatOfPoint (mat .toArray ());
3639
3740 Rect r = Imgproc .minAreaRect (mat ).boundingRect ();
3841 boundingBox = new Rectangle (r .x , r .y , r .width , r .height );
39-
4042 loadPoints (mat .toArray ());
4143 }
42-
4344
4445 public void loadPoints (Point [] pts ){
4546 points = new ArrayList <PVector >();
@@ -68,6 +69,25 @@ public Contour getPolygonApproximation(){
6869 return new Contour (parent , approx );
6970 }
7071
72+ public Contour getConvexHull (){
73+
74+ MatOfInt hull = new MatOfInt ();
75+ MatOfPoint points = new MatOfPoint (pointMat );
76+
77+
78+ Imgproc .convexHull (points , hull );
79+ Point [] hp = new Point [hull .height ()];
80+
81+ for (int i = 0 ; i < hull .height (); i ++){
82+ int index = (int )hull .get (i ,0 )[0 ];
83+ hp [i ] = new Point (pointMat .get (index ,0 ));
84+ }
85+ MatOfPoint hullPoints = new MatOfPoint ();
86+ hullPoints .fromArray (hp );
87+
88+ return new Contour (parent , hullPoints );
89+ }
90+
7191 public void draw (){
7292 parent .beginShape ();
7393 for (PVector p : points ) {
0 commit comments