Ask Your Question

How to place one rectangle inside another one without intersections?

asked 2017-12-31 06:27:29 -0500

My JavaFX applications do the follow: opens background image, opens foreground image and foreground image should be placed inside background "randomly" in such way that foreground image should not intersect contour of background image.

Let me show example, where coordinates of foreground image are hardcoded:

image description

So I did the follow: Using snippet from this question I combine background image and foreground image into one.

After this I tried to find contour of this combined image using code from this article. And it looks like OpenCV finds contours of background image successfully.

But I should place foreground image inside background image, adding some random factor in order to foreground can be inside contour in any place and with any rotation factor, but not intersect contour.

If this question or approach are incorrect, sorry, I'm newbie in OpenCV. This code

Imgproc.findContours(gray, contours, new Mat(),
                    Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);

returns ArrayList in contours of such objects

Mat [ 91*1*CV_32SC2, isCont=true, isSubmat=false, nativeObj=0x1cbdcce0, dataAddr=0x1cac3800 ]

and I have no idea how to use it.

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted

answered 2017-12-31 07:07:51 -0500

berak gravatar image

you can use pointPolygonTest() with your contour, and the 4 corners of your overlay rectangle.

edit flag offensive delete link more


It means that I should iterate over and over until I will find the correct position of inner rectangle. Don't we have more fast approach to manipulate with contours in terms of intersections or something like this ?

DrJeston gravatar imageDrJeston ( 2017-12-31 09:58:28 -0500 )edit

answered 2020-05-21 04:55:26 -0500

kpachinger gravatar image

The best test would be bitwise_and for any positions. If the output area equals the foreground area, you have certainty.

If background is concave, foreground corners could test inside while overlapping contour. Is your test so robust as to fit secondary transforms such as offset and rotation, or size mismatch? Is it then fast enough?

edit flag offensive delete link more

Question Tools

1 follower


Asked: 2017-12-31 06:22:52 -0500

Seen: 272 times

Last updated: May 21 '20