28

Below are 2 rectangles. Given the coordinates of the rectangle vertices - (x1, y1)...(x8, y8), how can the area of the overlapping region (white in the figure below) be caclulated?

Note that:

  1. Coordinates of points might be any
  2. Rectangles may or may not overlap
  3. Assume area is 0 when rectangles don't overlap, or they overlap at point or line.
  4. If one rectangle is inside the other, then calculate area of smaller rectangle.

enter image description here

andand
  • 17,134
  • 11
  • 53
  • 79
Vadim
  • 1,223
  • 2
  • 17
  • 26
  • To be more specific, you mean `rectangles` with aligned axes, correct? – Codie CodeMonkey Nov 04 '11 at 15:03
  • Paralelepipeds are 3 dimensional polydedra, which can have non-right angle intersections. Your image seems to show a pair of aligned rectangles. – Parker Coates Nov 04 '11 at 15:04
  • DeepYellow: Yes, you are correct. – Vadim Nov 04 '11 at 15:05
  • Parker: sorry for my typo, I mean rectangle. – Vadim Nov 04 '11 at 15:06
  • And you want to find *the square of the area*? Or just the area? Or the vertices of the intersection? – Beta Nov 04 '11 at 15:06
  • Once again, sorry for my typo, I mean find square of white *region*. – Vadim Nov 04 '11 at 15:08
  • @Vadim: you can probably transform the coordinate system so that the lines are either vertical or horizontal, then solve the problem in that transformed space and revert to the original coordinate system... – David Rodríguez - dribeas Nov 04 '11 at 15:09
  • David Rodríguez: one rectangle may be vertical, byt another rectangle might not. Points of rectangles might be any. – Vadim Nov 04 '11 at 15:15
  • @Vadim So it's not what DeepYellow said, is it? And sorry, but I still didn't get the meaning of *square*. Do you mean the area of the overlapping region, which in case of non-aligned rectangles need not be a rectangle (or even a square) itself. – Christian Rau Nov 04 '11 at 15:31
  • 2
    The area of the overlapping region: yes, thats what I mean. – Vadim Nov 04 '11 at 16:07
  • @Vadim, I've written the standard way of handling this in as much detail as I'm willing to do. Kindly modify your question with the corrections we've discussed so that others can benefit from this when they search for "rectangle-rectangle intersection." By the way, my algorithm works for any pair of *convex* polygons. – Codie CodeMonkey Nov 04 '11 at 16:13
  • DeepYellow: I'm working on modification right now. – Vadim Nov 04 '11 at 16:26
  • @Vadim Aha! The question gets much clearer now. +1 for the new version! Though check the ordering of the points in the picture. The first rectangle is clockwise, whereas the second one is counter-clockwise. Though that's a minor detail, It could create confusion. – Christian Rau Nov 04 '11 at 16:46
  • Christian Rau: thanks for seeing this 'counter-clockwise' detail, I updated it. – Vadim Nov 04 '11 at 16:56
  • @Vadim As a little unrelated side note for the workings of StackOverflow: use the @-syntax if you want to address somebody with a comment, otherwise they won't get notified of your response. – Christian Rau Nov 04 '11 at 17:18
  • @ChristianRau: they won't get notified of your response: they are notified by email or somehow else? – Vadim Nov 04 '11 at 17:28
  • @Vadim No, somehow else: if you address somebody with the @-syntax, they get notified of the response in the "responses"-tab on their user page. And there will also be a little icon in the top left corner of each StackExchange site (next to the word "StackExchange"), indicating that they have new responses. Have you never noticed these things? This won't work if you don't use the @-syntax. In this case they will only eventually notice your response if they happen to actively monitor these comments or if they are the posters of the question/answer your comment belongs to. – Christian Rau Nov 04 '11 at 17:52

6 Answers6

17

Since you stated that the rectangles may not be aligned, possible answers may be nothing, a point, a line segment, or a polygon with 3-8 sides.

The usual way to do this 2d boolean operation is to choose a counterclockwise ordering of the edges, and then evaluate edge segments between critical points (intersections or corners). At each intersection you switch between an edge segment of the first rectangle to an edge of the second, or visa-versa. You always pick the segment to the left of the previous segment.

enter image description here

There are LOTS of details, but the basic algorithm is to find all intersections and order them on their edges with an appropriate data structure. Choose an intersection (if there is one) and choose a line segment leading away from that intersection. Find the segment of the other rectangle to the left of the chosen starting segment. In the picture, we choose the green segment on intersection a (in the direction indicated by the arrow) as the reference segment. The segment of the other rectangle that is to the right, is the segment from a to b. Use that as the next reference segment, and choose a green segment to the left of it. That's the segment from b to c. Find segment cd the same way. The next segment is from d to the corner, so the corner is in the vertex list for the intersection as well. From the corn we get back to a.

To choose the left side each time, you use the determinate of the coordinates of the direction vectors for the edges that meet. If the determinant for the ordered pair of directed edges is positive, you're going the right way.

Now that you have the vertices of the intersection polygon, you can use the surveyor's formula to get the area.

Some of the details that I'm leaving to you are:

  • What if a corner is coincident to to an edge or vertex of the other triangle?

  • What if there are no intersections? (one rectangle is inside the other, or they are disjoint--you can use point-in-polygon checks to figure this out. See the Wikipedia article on polygons.

  • What if the intersection is a single point or a segment?

Codie CodeMonkey
  • 7,669
  • 2
  • 29
  • 45
  • Points of rectangles might be *any*. So while one rectangle might be vertical another one might not. – Vadim Nov 04 '11 at 15:16
  • In that case you wouldn't have either a rectangle or (as you said originally a "square" of intersection). The answer might be empty, a single point, a line segment, triangle, etc., up to an octagon! So the original question has lots of flaws. – Codie CodeMonkey Nov 04 '11 at 15:23
  • question has lots of flaws: seems to be so... I will now update the question a bit. – Vadim Nov 04 '11 at 16:11
7

There is another way that you may find interesting, but maybe not applicable in this case, and that is:

  1. determine the minimum rectangle( whose sides are parallel to coordinate axes ) that contains both of the given rectangles, lets call that new one a bounding box.
  2. pick a random dot that is in the bounding box and check whether it is in both rectangles or not
  3. repeat step 2 for as long as you want( it depends on the precision you want for your result ), and have two counters, one to keep track of the number of dots inside both of the rectangles, and the other which is the number of repetitions of step 2
  4. the final solution is the area of the bounding box multiplied by the number of dots inside both rectangles and then divided by number of repetitions of step 2, or in a form of a formula:

    intersection_area = bounding_box_area * num_of_dots_inside_both / num_of_repetitions

The result will, of course, be more precise when the number of repetitions is larger. By the way, this method is called Monte Carlo method.

Zvonimir
  • 339
  • 1
  • 7
1

You can calculate the intersection points by solving intersection equations for all pairs of sides of the figures: /frac{x - a}{b - a} = /frac{x - c}{d - c}

The points that you obtain in such a fashion can lie on the sides of the paralelepide, though they must not. You have to check whether the intersection points you obtained by solving the equations lie on the sides of the figure or not. If they do, you can calculate the length of the sides of the figure that stretch out into the inside of the both figures, and calculate the square of the intersection by taking their multiple.

I guess my method sounds a bit over-complicated, but this is the first thought that came to my mind.

Pavlo Dyban
  • 1,297
  • 2
  • 15
  • 28
0

If you happen to use Qt then the intersection can be computed as QPolygonF intersection. Roughly as so:

QPolygonF p1,p2, intersected;
p1 << QPointF(r1x1,r1y1) << ... << QPointF(r1x4, r1y4);
p2 << QPointF(r2x1,r2y2) << ... << QPointF(r2x4, r2y4);
intersected = p1.intersected(p2);

float area = polyArea(intersected); // see code block below

(r1 = rectangle 1, r2 = rectangle 2, with 4 respective x and y coordinates).

Now compute the area (using the already mentioned Shoelace formula):

inline float polyArea(const QPolygonF& p)
{
    //https://en.wikipedia.org/wiki/Polygon#Area_and_centroid
    const int n = p.size();
    float area = 0.0;
    for (int i=0; i<n; i++)
    {
        area += p[i].x()*p[(i+1)%n].y() - p[(i+1)%n].x()*p[i].y();
    }
    if (area < 0)
        return -0.5*area;
    else
        return 0.5*area;
}

My code here: public domain

DomTomCat
  • 8,189
  • 1
  • 49
  • 64
0

Maybe you need to use opencv. Use the fillPoly() function to generate a rectangle. Make sure the fill rectangle is white (255, 255, 255). Then use the copyTo() function and you will get the overlap area. Then check the value of each pixel , if it is white then +1.

john li
  • 1
  • 1
0

It may help to think of the problem in terms of triangles instead of rectangles. Finding the area of a triangle given three points in space is relatively straight forward.

You can find the intersecting area by subtracting the rectangle area by the sum of the areas of the triangles as shown in the image below.

Triangulation

Essentially it becomes a triangulation problem.

There is a good intro here with some pointers on data structures and algorithms.

EDIT:

There are some free triangulation libraries that you could reuse.

If you know the area of the two triangles you are starting off with you can find the total area of the union of the rectangles, so the intersection would be the total area of both rectangles - the union area.

ckoo
  • 219
  • 2
  • 5
  • The Surveyor's Formula mentioned in @DeepYellow's answer is much simpler than subtracting triangles. And dealing with triangles in the general case when the figure might not look like that picture would be a huge mess. – aschepler Nov 06 '11 at 23:35
  • I pointed out this solution as it does not require the coordinates to be rotated. (The shown figure is one of the hardest to deal with. i.e. it is the biggest mess you will get.). – ckoo Nov 06 '11 at 23:51
  • @ckoo, My solution doesn't require rotating rectangles either. That solution was when the OP had a drawing that implied that the rectangles were axis aligned. I'll modify my response to make it clear that no rotation is needed. – Codie CodeMonkey Nov 07 '11 at 08:14
  • Just for the record, for anyone reading and struggling with this, this answer is unfortunately essentially wrong. There are indeed many such problems where there is a "very clever" solution involving making the problem in to triangles. **However, very sadly**, the rectangle-rectangle problem simply does not have such a "clever triangles" solution. DeepYellow has given what is unfortunately the one and only answer. (Unless in the future someone invents an incredible algo for this! :) ) – Fattie Sep 12 '12 at 09:52