# 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;

1
1

Official site

GitHub

Wiki

Documentation

## Stats

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

Seen: 22,525 times

Last updated: Jul 27 '15