本文介绍了在Python中查找多个重叠矩形的相交区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用此处显示的算法: https://discuss.leetcode.com/topic/15733/my-java-solution-sum-of-areas-overlapped-area

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.

如果我知道每个矩形的长度,宽度,我将如何继续查找相交的面积,例如3或4或5,等等.

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?

推荐答案

形状是像这样的东西的好图书馆.

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()

这篇关于在Python中查找多个重叠矩形的相交区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 07:53