Ask Your Question
0

What is the correct way to find and implement a bounding box mask?

asked 2018-09-04 08:29:38 -0600

bfialkoff gravatar image

Hi I'm trying to find the arbitrarily oriented bounding box of a binary image. This seems like a pretty trivial problem but I've spent 2 days trying to find the correct way to use minAreaRect() and to use it to create a simple binary mask.

Can anyone please help, in java please?

Thank you to all.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2018-09-04 08:46:18 -0600

berak gravatar image

updated 2018-09-04 09:46:33 -0600

java is somewhat clumsy here, but it's just a few lines:

Mat mask = Mat.zeros(400,400,CvType.CV_8U); // all black

// your RotatedRect will come from minAreaRect(), this is just demo data !
RotatedRect rc = new RotatedRect(Point(200,200), new Size(200,100), 23);

// retrieve corner points:
Point[] p = Point[4];
rc.points(p);

// draw white, filled poly:
MatOfPoint mp = new MatOfPoint(p);
Imgproc.fillConvexPoly(mask, mp, new Scalar(255));

image description

[edit]

  • usually you need a contour as input for minAreaRect(), see tutorial and some conversion code (sorry, untested):

    List<MatOfPoint> contours = new ArrayList<>();
    Imgproc.findContours(cannyOutput, contours, ...);
    Point [] pts = contours.get(i).toArray();
    RotatedRect rc = Imgproc.minAreaRect(new MatOfPoint2f(pts));
    
  • sorry, i was just trying out latest 4.0, where all drawing stuff was moved to Imgproc for consistency, but yes, it's likely in Core with your version

edit flag offensive delete link more

Comments

Thanks! It works like a charm but what is the correct way to get a RotatedRect from minAreaRect? Currently this is what I'm trying to do.

MatOfPoint2f Points = new MatOfPoint2f();
Core.findNonZero(paper_mat,Points);
RotatedRect minRect=Imgproc.minAreaRect(Points);

and its not working. paper_mat is a binary image that looks basically like the image you posted just not quite so neat.

Also for brevity fillConvexPoly is in Core not Imgproc

Thanks again

bfialkoff gravatar imagebfialkoff ( 2018-09-04 09:03:14 -0600 )edit

When you write

Point [] pts = contours.get(i).toArray();

Do you mean contours.size () in place of i In the tutorial i is iterating through contours.size () but here we're turning the whole thing into an array. It would make sense...

bfialkoff gravatar imagebfialkoff ( 2018-09-04 10:08:14 -0600 )edit

yea, sorry. findContours() returns a list of contours, and get(i) retrieves one of those.

you probably want get(0) (the first, and ?only?)

berak gravatar imageberak ( 2018-09-04 10:21:14 -0600 )edit

I'll need to double check but if I do get(0) it only draws a point.

So what set pts=contours.toArray () ?

bfialkoff gravatar imagebfialkoff ( 2018-09-04 10:25:35 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2018-09-04 08:29:38 -0600

Seen: 1,595 times

Last updated: Sep 04 '18