# How to find if 2 rectangles are overlapping each other

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/...

edit retag close merge delete

Sort by ยป oldest newest most voted

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)]


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

bool intersects = ((A & B).area() > 0);

more

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;

( 2015-07-27 04:06:08 -0500 )edit
1

edited, look again.

( 2015-07-27 04:13:01 -0500 )edit
1

Ah right I didnt think of that.. lol.

Thanks so much

( 2015-07-27 04:15:44 -0500 )edit

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

( 2015-07-27 07:55:42 -0500 )edit