What is an algorithm for determining the total area of two rectangles that are intersecting and may be rotated off the coordinate axes?
-
2related but does not have the rotation possibility requirement: [total area of intersecting rectangles](http://stackoverflow.com/questions/4549544/total-area-of-intersecting-rectangles/4555164#4555164) – jball Dec 29 '10 at 23:39
-
I would like to point out that the currently highest rated answer by Tom Medley, while very interesting, is *not* the easiest approach. The straightforward solution is to use one of the algorithms for [convex polygon intersection](http://stackoverflow.com/a/13105297/145999) (like Sutherland-Hodgman) to find the intersection between both rectangles, then calculate the [area of the intersection](http://www.mathwords.com/a/area_convex_polygon.htm), then calculate the area of the union as Area(rect1) + Area(rect2) - Area(intersection). This is also outlined in the answer by Alexandre C. – HugoRune Nov 24 '13 at 01:04
3 Answers
Here's roughly what you need to do, expressed as generally as possible, but covering all possibilities:
- Work out the class of intersection. I.e. How many edges does the intersection area have? It could be anything from 0 to 8.
- Find all vertices of the intersection. This will be all intersections between the edges of the rectangles, and associated corners of the rectangles themselves. Working this bit out is the most complex/tedious.
- Work out the area of the intersection, by dividing it up into triangles if necessary.
Here's all the ways the rectangles can intersect:
Update
I've had some thoughts, and the best way to categorize the intersection is to trace round the perimeter of each rectangle and count the number of times each edge intersects another edge. You'll get a vector, e.g. for a six sided intersection area: {1,1,1,1},{0,1,1,1}, and for 8: {2,2,2,2},{2,2,2,2}. The two special cases you'll need to check for are when one rectangle completely encloses the other and when the edges are in line. You'll need to do careful checks, but this would be the starting point for a function to categorize the intersection.

- 32,953
- 42
- 145
- 236
-
1As the rectangles may be tilted, the intersection could be also a triangle – Dr. belisarius Dec 29 '10 at 23:59
-
3There's also the possibility that the intersection could be a 5, 6, 7 or or 8-sided figure. – Michael Burr Dec 30 '10 at 00:21
-
-
@jball I'm not prepared to provide a full solution! And you would be able to optimize the calculation of the area once you can categorize it certainly. – fredley Dec 30 '10 at 16:45
-
2
-
2Another case: two rectangles of the same size precisely overlapping (the overlapped area is the total area of either rectangle). – Dave Jarvis Aug 08 '12 at 20:36
Area(R1 union R2) = Area(R1) + Area(R2) - Area(R1 intersection R2), so you can calculate the area of the intersection to have the area of the union.
Intersections of two rectangles (or two convex polygons) are simple:
- They are convex polygons
- Their points are characterized as follows: intersection points of any pair of edges, and points of one rectangle which are inside the other.
So it goes like this:
- L is an initially empty linked list
- R1 has edges e1, e2, e3, e4, R2 has edges f1, f2, f3, f4. Compute intersection points of ei and fj, for all i,j=1,2,3,4. Add them to list L.
- For each vertex v of R1, if v is inside R2, add it to L.
- For each vertex w of R2, if w is inside R1, add it to L.
The convex hull of points in L is your intersection. As every point in L is on the boundary of the intersection, you can triangulate it and compute its area. Easy:
- L = [x0, x1, ... ]
- Sort points in L according to the angle of (xi - x0) with respect to an horizontal line passing through x0
- First triangle is x0, x1, x2
- Second triangle is x0, x2, x3
- nth triangle is x0, x(n+1), x(n+2)
The area of a triangle is given by Heron formula:
- a, b, c are edge lengths
- s = 0.5 * (a + b + c)
- area = sqrt(s * (s - a) * (s - b) * (s - c))
but beware of computing s - a, s - b and s - c independantly since you can encounter roundoff error (what if c ~ a and b << a for instance ?)

- 55,948
- 11
- 128
- 197
-
Is calculating the intersection of each edge in the first rectangle to every edge in the second rectangle really the best solution? – jball Dec 30 '10 at 16:39
-
@jball: for rectangles, it gives you 16 such tests. For intersecting more complex convex polygons, you may want to use quadtrees or similar to avoid most of the tests. Note however that after a change of variables to put R1 along coordinate axes, these tests are straightforward. – Alexandre C. Dec 30 '10 at 16:43
-
Thinking about it more, finding the intersection just creates unnecessary calculations. A better method is to find the vertices of the entire union, and then calculate the area of that. It reduces the area calculations from 3 (2 that are trivial) down to 1. And there are better algorithms than triangulation for calculating the area of a polygon. – jball Dec 30 '10 at 17:07
-
Example that handles convex and concave polygons: http://www.mathopenref.com/coordpolygonarea.html – jball Dec 30 '10 at 17:09
-
@jball: Finding the vertices of the union seems as difficult, and less natural than what I wrote, which took me 5 minutes to figure out. And yes, there are better algorithms than triangulation for the area of a convex polygon, this one was on top of my head. – Alexandre C. Dec 30 '10 at 17:36
-
@jball: the method you link to seems numerically horrible (all those determinants xy - yx are very prone to roundoff error). Moreover, it is exactly computing the area by triangulation, by the same method I use, but instead of Heron's formula, it uses the cross product. Heron's formula is likely to be numerically more accurate, provided that eg. you compute (s - a) by 0.5 * (-a + b + c). – Alexandre C. Dec 30 '10 at 17:39
-
@jball: and your linked to method does **not** handle non convex polygons. – Alexandre C. Dec 30 '10 at 17:41
-
@Alexandre C. - First point - rounding errors will not happen (See the [further explanations](http://www.attewode.com/Calculus/AreaMeasurement/area.htm) that are available on the web). Second point, using Heron's requires more code and more processing (finding square roots is expensive). Third point, it **does** handle concave polygons. As a matter of fact it handles all polygons except for crossed polygons. Those will never occur in this situation. – jball Dec 30 '10 at 17:52
-
@Alexandre C. - Just noticed your comment about finding the union - it may seem less natural, but it's more direct to the problem, and no more difficult to write out. Your algorithm above works perfectly simply by changing "inside" to "outside" in *For each vertex v of R1, if v is inside R2, add it to L.* and the symmetrical statement for the vertices of R2. – jball Dec 30 '10 at 17:56
-
@jball: Okay, this is in fact Stokes formula, so it will work for any simply connected "Jordan" polygon (ie. **no holes**, **no self-intersections**). For the numerical accuracy, I still think you expose yourself to roundoff error by computing the area this way. And after reading your comment, finding the union is as natural as finding the intersection. – Alexandre C. Dec 30 '10 at 22:21
-
@Alexandre C. - yes, it's a special case of Stokes. You can derive the cross product method yourself if you wish to understand why there won't be any roundoff errors but it's well established as a direct (not approximate) method for calculating the area of a polygon. – jball Dec 30 '10 at 22:41
-
@jball: It will have roundoff error when xi and yi are moderate and the total area small (ie. for instance xi, yi ~ 10000 and area ~ 1 or so, you expect to lose 4 figures). You'll cancel a lot of digits when performing the cross products (8 or so in our case), and thus lose more precision than you would lose by other methods. – Alexandre C. Dec 30 '10 at 23:05
-
-
@jball: when you substract close numbers, ie. 10000001 - 10000000 = 1, but you have now one significant digit where you had 8 before. – Alexandre C. Dec 31 '10 at 00:43
-
@Alexandra C. - I see. This doesn't yield a different total result from the other methods though, does it? – jball Dec 31 '10 at 01:20
Ok, you have 3 possibilities: 1. Rectangles don't intersect 2. One rectangle is completely contained within the other (or they coincide) 3. The result of intersection is some convex polygon. You compute the area of a polygon by breaking it into triangles (by drawing segments from the first vertex to every other except for adjacent once). The you sum up the areas. You can use Herodot's theorem to calcaulate triangle's area and that's where midlle school geometry comes in.

- 2,848
- 3
- 23
- 38
-
3
-
@belisarius - actually I don't think it can be concave. Of course this answer makes no sense and I downvoted it, but I don't see how the intersection could be concave... – IVlad Dec 30 '10 at 00:42
-
IVlad, could you provide an example (in terms of some array of points so I'll get a concave polygon)? Thanx – Nickolodeon Dec 30 '10 at 00:44
-
1@Nickolodeon - you can't just sum up the areas, because then you will sum the area of the intersection twice. So you need to subtract the area of the intersections. How do you propose we do that? – IVlad Dec 30 '10 at 00:45
-
IVlad, how about summing up the areas of 2 rectangles and subtract polygonal area from the result, ha? I know it's tough for those that downvote answers without making one more step furher into thinking. – Nickolodeon Dec 30 '10 at 00:54
-
-
As a matter of fact, fredley proposes a right way to go (I just don't see how angles can be>180!). You need to start constructive comment on that, jball. My solution is just more instructive. – Nickolodeon Dec 30 '10 at 01:09
-
1Okay, continue your hand-waving. How can any of us here be a match for someone who can't even spell right and uses advanced stuff like Herodot's theorem to compute triangle areas? – IVlad Dec 30 '10 at 01:13
-
2IVlad, you are missing the point. If you are more interested in a correct spelling then you should probably dwell on humanitarian forums. – Nickolodeon Dec 30 '10 at 01:15
-
@Nickolodeon What? Your "solution" glosses over how to determine what the intersecting polygon is and provides what looks to be a clumsy method for calculating its area. These are actually the most interesting parts of the problem. It's quite a stretch to say you provided an instructive solution. – jball Dec 30 '10 at 04:12
-
@jball, finding convex polygon of intersections is not hard, at least very bad algorithm is: you can find intersection of 4 * 4 segments and after that find the convex polygon (oh yes by convex hull!!), and calculating area of convex polygon is as easy as google search http://www.mathwords.com/a/area_convex_polygon.htm – Saeed Amiri Dec 30 '10 at 14:01
-
@Saeed not finding an elegant solution for calculating the intersection of the two rectangles is what has prevented me from posting an answer. Your link on calculating the area of the resulting polygon just proves my point to @Nickolodeon about the above answer's area calculation method being unnecessarily awkward and inefficient. – jball Dec 30 '10 at 16:35