【问题标题】:Finding the area of intersection of multiple overlapping rectangles in Python在Python中查找多个重叠矩形的交集区域
【发布时间】:2016-12-27 06:10:46
【问题描述】:

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

但是,该算法仅处理仅查找两个重叠矩形的区域。

如果我知道每个矩形的长度和宽度,我将如何继续寻找 3、4 或 5 等重叠矩形的交集区域?

【问题讨论】:

  • 您是在寻找 n 个矩形的并集还是交集?如果相交,您是要计算任何个重叠区域,还是只计算所有个矩形重叠的地方?
  • 交点,所有矩形重叠的地方
  • edit您的问题包含这样的重要细节,这样人们就不会浪费时间解决错误的问题。 (请注意,您收到的第一个答案以“我假设您要查找 union...的区域...”开头。)

标签: python area rectangles


【解决方案1】:

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?
  • 看文档:pypi.python.org/pypi/Shapely。如果你使用的是 Anaconda dist,你可以在命令行中使用conda install shapely(推荐)。
  • 好吧,我用 conda 来执行那行安装代码,现在它说“用法:安装 [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m模式] [-o 所有者] 文件 1 文件 2 安装 [-bCcpSsv] [-B 后缀] [-f 标志] [-g 组] [-m 模式] [-o 所有者] 文件 1 ... fileN 目录安装 -d [- v] [-g 组] [-m 模式] [-o 所有者] 目录..." 我现在该怎么办
  • 好吧,如果我们假设所有输入矩形都相互交叉,那么所提出的 for 循环计算似乎是合理的。但是一般情况下给定一个矩形列表,如何高效查找多个矩形是否有重叠区域(>2)。
猜你喜欢
  • 2010-12-05
  • 1970-01-01
  • 1970-01-01
  • 2019-12-12
  • 2012-06-21
  • 1970-01-01
  • 2011-09-14
  • 1970-01-01
  • 2018-05-24
相关资源
最近更新 更多