Getting involved in computer vision project requires me to make myself familiar with OpenCV. And today, I’ve just withnessed one of its powerful functions which is related to two-dimensional rectangle operation. It supports intersection (overlapping) and unification (union) of two different rectangles.

#### Intersection

If we want to find out whether two different rectangles are intersecting each other, then we can use ‘&’ operator. By using ‘&’ operator, we can get the intersecting rectangle between two rectangles. Thus, if the intersecting rectangle area is larger than 0 (or any threshold), then it is intersecting and otherwise it is not. Here is an example:

Rect2d r1(x1, y1, width1, height1); Rect2d r2(x2, y2, width2, height2); Rect2d r3 = r1 & r2; if (r3.area() > 0) { cout << "Intersecting Rectangles" << endl; } else { cout << "Non-intersecting Rectangles" << endl; }

Figure below, shows the result of finding intersecting area two rectangles. The red rectangles are r1 and r2, the blue one is the intersecting area between them.

If one of the rectangle is fully enclosed by the other rectangle, then the r3 area will be the same with either r1 or r2. We can check this condition by adding another if-statement as follows:

if (r3.area() > 0) { if (r3.area() == r2.area()) { cout << "r2 is inside r1" << endl; } else if (r3.area() == r1.area()) { cout << "r1 is inside r2" << endl; } else { cout << "Overlapping Rectangles" << endl; } } else { cout << "Non-overlapping Rectangles" << endl; }

Figure below shows the result of finding intersecting area between two rectangles in which one of them are enclosed by the other one. The blue rectangle marks the enclosed one.

#### Union (Minimum covering rectangle)

If we want to find the union or minimum covering area between two rectangles, then we can use the ‘|’ operator. Here is the example:

Rect2d r1(x1, y1, width1, height1); Rect2d r2(x2, y2, width2, height2); Rect2d r3 = r1 | r2;

The green rectangle (r3) shown in figure below is the the union of red rectangles (r1 and r2).

Those are two functions (intersection and union) that have already been provided by rectangle class in OpenCV. So if you are working with OpenCV, I believe this will save your time.