我试着用这里显示的算法面积:https://discuss.leetcode.com/topic/15733/my-java-solution-sum-of-areas-overlapped-area查找多个重叠的矩形的交集在Python
然而,该算法只涉及只发现两个重叠的矩形的面积。
如果我知道每个矩形的长度和宽度,我将如何继续寻找说3或4或5等交叠矩形的交点的区域?
我试着用这里显示的算法面积:https://discuss.leetcode.com/topic/15733/my-java-solution-sum-of-areas-overlapped-area查找多个重叠的矩形的交集在Python
然而,该算法只涉及只发现两个重叠的矩形的面积。
如果我知道每个矩形的长度和宽度,我将如何继续寻找说3或4或5等交叠矩形的交点的区域?
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()
如何在mac OS X上安装shapely.geometry? – Falcon2908
看文档:https://pypi.python.org/pypi/Shapely。 如果您使用的是Anaconda dist,则可以在命令行中使用'conda install shapely'(推荐)。 – benten
好吧,我用conda来执行那个安装代码行,现在说“用法:安装[-bCcpSsv] [-B后缀] [-f标志] [-g组] [-m模式] [-o所有者] file1 file2 install [-bCcpSsv] [-B后缀] [-f标志] [-g组] [-m模式] [-o所有者] file1 ... fileN目录 install -d [-v] [ -g组] [-m模式] [-o所有者]目录...“我现在要做什么 – Falcon2908
您是否在寻找_n_矩形的联合,或交集?如果相交,你想计算_any_重叠的区域,还是只在矩形重叠的地方? –
交叉点,其中所有的矩形重叠 – Falcon2908
请编辑您的问题以包含这样的重要细节,这样人们就不会浪费时间解决错误的问题。 (请注意,您收到的第一个答案以“我假设您想要查找**联盟的区域** ...”开头)。 –