python - 计算两个矩形之间的重叠面积

标签 python numpy matplotlib polygon shapely

enter image description here

我想计算红色和蓝色矩形之间的重叠区域“灰色区域”。

每个矩形由其四个角坐标定义。重叠区域的结果单位是单位正方形。

我无法想象我该怎么做?

我们将不胜感激任何有创意的评论。

最佳答案

这种类型的交集很容易通过“最大值的最小值”和“最小值的最大值”的想法来完成。要写出来,需要对矩形有一个特定的概念,为了清楚起见,我将使用一个命名元组:

from collections import namedtuple
Rectangle = namedtuple('Rectangle', 'xmin ymin xmax ymax')

ra = Rectangle(3., 3., 5., 5.)
rb = Rectangle(1., 1., 4., 3.5)
# intersection here is (3, 3, 4, 3.5), or an area of 1*.5=.5

def area(a, b):  # returns None if rectangles don't intersect
    dx = min(a.xmax, b.xmax) - max(a.xmin, b.xmin)
    dy = min(a.ymax, b.ymax) - max(a.ymin, b.ymin)
    if (dx>=0) and (dy>=0):
        return dx*dy

print area(ra, rb)
#  0.5 

如果您不喜欢 namedtuple 表示法,您可以使用:

dx = max(a[0], b[0]) - min(a[2], b[2])

等等,或者你喜欢的任何符号。

关于python - 计算两个矩形之间的重叠面积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27152904/

相关文章:

python - 高效返回数组中第一个满足条件的值的索引

python - 从 python 启动和停止外部进程

python - 根据输入值在 Python 中创建字典

python - AttributeError 列表对象没有添加属性

python - 在 python pandas 中查找每个日期的字母计数

python - 条形图中令人讨厌的空白(matplotlib,Python)

python - 从 SQLAlchemy 调用存储过程

python - 为什么需要 Visual C++ Installer 来为 Python 安装 numpy 包?

python - 如何向子图添加轴?

python - matplotlib 中具有零值的对数标度图