在Python中查找多个重叠矩形的交集区域

5

2
你是在寻找_n_个矩形的并集还是交集?如果是交集,你想要计算任何重叠区域,还是只有所有矩形都重叠时才计算? - Kevin J. Chase
所有矩形重叠的交集 - Lorren112
2
请[编辑]您的问题,包括重要细节,这样人们就不会浪费时间解决错误的问题。(请注意,您收到的第一个答案以“我假设您想找到联合的面积...”开头。) - Kevin J. Chase
你也可以看一下这段代码,https://stackoverflow.com/a/75378206/16733101 - Hamzah
1个回答

9

Shapely 是一个很好的用于此类问题的库。

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

为了更直观地理解这里正在发生的事情,我绘制了矩形及其交集部分:
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


我该如何在Mac OS X上安装Shapely.geometry? - Lorren112
2
请查看文档:https://pypi.python.org/pypi/Shapely。如果您使用Anaconda发行版,建议在命令行中使用“conda install shapely”。 - benten
好的,我使用conda执行了那行安装代码,现在它显示 "usage: install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode]                [-o owner] file1 file2        install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode]                [-o owner] file1 ... fileN directory        install -d [-v] [-g group] [-m mode] [-o owner] directory ... " 现在我该怎么办? - Lorren112
2
好的,假设我们假设所有输入的矩形都相互交叉,那么提出的for循环计算似乎是合理的。但一般情况下,如果给定一个矩形列表,如何有效地找到是否存在多个矩形(>2)的重叠区域。 - galactica

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接