Ask Your Question
3

How to find if 2 rectangles are overlapping each other

asked 2015-07-27 03:36:14 -0600

Nbb gravatar image

updated 2017-12-26 10:55:35 -0600

Hello Forum,

For the following image below, how do i determine if the smaller rectangle is overlapped / partially overlapped with the larger one ? I have their coordinates in frame i.e. rect.x and rect.y.

Should I just use FLANN or Nearest Neighbour or is there a better way ? http://docs.opencv.org/modules/flann/...

image description

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
8

answered 2015-07-27 03:50:25 -0600

berak gravatar image

updated 2015-07-27 03:57:06 -0600

cv::Rect has union / intersection operators:

union : rect1 | rect2

intersection: rect1 & rect2

here's an example:

Rect A(20,20,80,80); // blue
Rect B(60,60,60,60); // blue

Rect C = A & B;   // red
Rect D = A | B;   // green

cerr << "A" << A << endl;
cerr << "B" << B << endl;
cerr << "C" << C << endl;
cerr << "D" << D << endl;

Mat draw(200,200,CV_8UC3,Scalar::all(0));
rectangle(draw,A,Scalar(200,0,0),2);
rectangle(draw,B,Scalar(200,0,0),2);
rectangle(draw,C,Scalar(0,0,200),1);
rectangle(draw,D,Scalar(0,200,0),1);

A[80 x 80 from (20, 20)]
B[60 x 60 from (60, 60)]
C[40 x 40 from (60, 60)]
D[100 x 100 from (20, 20)]

image description

now, to find out, if 2 Rects overlap, just check the area of the intersection:

bool intersects = ((A & B).area() > 0);
edit flag offensive delete link more

Comments

Hello thanks !

I would like the output to be a boolean though , true or false. Do u know how I can achieve that ? I have tried that method before proceeding onto nearest neighbour / FLANN as I have no clue how to get a boolean out of 'C' from Rect C = A & B;

Nbb gravatar imageNbb ( 2015-07-27 04:06:08 -0600 )edit
1

edited, look again.

berak gravatar imageberak ( 2015-07-27 04:13:01 -0600 )edit
1

Ah right I didnt think of that.. lol.

Thanks so much

Nbb gravatar imageNbb ( 2015-07-27 04:15:44 -0600 )edit

Do accept the answer of @berak if that is what you needed ;)

StevenPuttemans gravatar imageStevenPuttemans ( 2015-07-27 07:55:42 -0600 )edit

Question Tools

2 followers

Stats

Asked: 2015-07-27 03:36:14 -0600

Seen: 40,793 times

Last updated: Jul 27 '15