opencv how to draw minAreaRect in java

2020-07-27 04:18发布

问题:

Hi I am trying to draw the rotated rect from minAreaRect but I find only code in python.

rect = cv2.minAreaRect(cnt)
box = cv2.cv.BoxPoints(rect)
box = np.int0(box)
cv2.drawContours(im,[box],0,(0,0,255),2)

How to draw it in java?

回答1:

I know this question is old, but recently I had the same problem so I decided to post the answer here.

Unfortunately, the OpenCV version I'm using on Android doesnt have the method rectangle that support RotatedRect as paramenter. So I had to improvise.

    Point points[] = new Point[4];
    rect.points(points);
    for(int i=0; i<4; ++i){
        Core.line(init, points[i], points[(i+1)%4], new Scalar(255,255,255));
    }


回答2:

I draw the the rotated rect from minAreaRect using the code like this:

rRect = Imgproc.minAreaRect(mop2f);

        Point[] vertices = new Point[4];  
        rRect.points(vertices);  
        for (int j = 0; j < 4; j++){  
            Imgproc.line(mat, vertices[j], vertices[(j+1)%4], new Scalar(0,255,0));
        }


回答3:

You could use drawContours like this:

Point[] vertices = new Point[4];
rotatedRect.points(vertices);
List<MatOfPoint> boxContours = new ArrayList<>();
boxContours.add(new MatOfPoint(vertices));
Imgproc.drawContours(out, boxContours, 0, new Scalar(128, 128, 128), -1);

With this method you could draw the contour and fill it with a solid color (something you can't do if you use Imgproc.line).



回答4:

Something like this:

MatOfPoint2f points = new MatOfPoint2f(new Point(1, 1), new Point(5, 1), new Point(4, 3), new Point(6, 2));
RotatedRect rrect = Imgproc.minAreaRect(points);