Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the area of intersection of multiple overlapping rectangles in Python

I tried to using the algorithm shown here: https://discuss.leetcode.com/topic/15733/my-java-solution-sum-of-areas-overlapped-area

However, that algorithm only deals with finding the areas of only TWO overlapped rectangles.

How would I go on about finding the area of the intersection of say 3, or 4 or 5, etc number of overlapping rectangles, if I know the length, breadth of each rectangle?

like image 439
Lorren112 Avatar asked Aug 20 '16 02:08

Lorren112


People also ask

How do you find the area of two overlapping rectangles?

We basically add areas of two rectangles. This includes the intersecting part twice, so we subtract the area of intersecting part. Similarly, we can compute area of 2nd rectangle. If the x_distance or y_distance is negative, then the two rectangles do not intersect.

What is the overlapping area?

The OverlapArea function is a Spatial Numeric measurement that calculates the total area (or length or count) of overlap between features in the current layer and features in the target layer.

How do you know if two rectangles are intersecting?

It is easy to visualize that the given two rectangles can not be intersect if one of the following conditions is true. Condition 1: When left edge of R1 is on the right of R2's right edge. ( That is , R1 is completely on the right of R2). Condition 2: When right edge of R1 is on the left of R2's left edge.


1 Answers

Shapely is a good library for stuff like this.

from shapely.geometry import box

# make some rectangles (for demonstration purposes and intersect with each other)
rect1 = box(0,0,5,2)
rect2 = box(0.5,0.5,3,3)
rect3 = box(1.5,1.5,4,6)

rect_list = [rect1, rect2, rect3]

# find intersection of rectangles (probably a more elegant way to do this)
for rect in rect_list[1:]:
    rect1 = rect1.intersection(rect)
intersection = rect1

To visualize what's happening here. I plot the rectangles and their intersection:

from matplotlib import pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon

# plot the rectangles before and after merging 

patches  = PatchCollection([Polygon(a.exterior) for a in rect_list], facecolor='red', linewidth=.5, alpha=.5)
intersect_patch =  PatchCollection([Polygon(intersection.exterior)], facecolor='red', linewidth=.5, alpha=.5)

# make figure
fig, ax = plt.subplots(1,2, subplot_kw=dict(aspect='equal'))
ax[0].add_collection(patches, autolim=True)
ax[0].autoscale_view()
ax[0].set_title('separate polygons')
ax[1].add_collection(intersect_patch, autolim=True)
ax[1].set_title('intersection = single polygon')
ax[1].set_xlim(ax[0].get_xlim())
ax[1].set_ylim(ax[0].get_ylim())
plt.show()

enter image description here

like image 108
benten Avatar answered Sep 28 '22 08:09

benten