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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27152904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:28:57  来源:igfitidea点击:

Calculate overlapped area between two rectangles

pythonnumpymatplotlibpolygonshapely

提问by Eric Bal

enter image description here

在此处输入图片说明

I want to calculate the overlapped area "THE GRAY REGION" between red and blue rectangles.

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

Each rectangle is defined by its four corner coordinates. The resulted unit of the overlapped area is unit square.

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

I could not imagine how can I do it?

我无法想象我该怎么做?

Any creative comments would be appreciated.

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

采纳答案by tom10

This type of intersection is easily done by the "min of the maxes" and "max of the mins" idea. To write it out one needs a specific notion for the rectangle, and, just to make things clear I'll use a namedtuple:

这种类型的交叉很容易通过“最大值中的最小值”和“最小值中的最大值”的想法来完成。为了把它写出来,需要一个特定的矩形概念,而且,为了让事情清楚,我将使用一个命名元组:

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 

If you don't like the namedtuple notation, you could just use:

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

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

etc, or whatever notation you prefer.

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

回答by Georgy

As this question has a shapelytag, here is a solution using it. I will use the same rectangles as in the tom10 answer:

由于这个问题有一个匀称的标签,这里有一个使用它的解决方案。我将使用与tom10 答案中相同的矩形:

from shapely.geometry import Polygon

polygon = Polygon([(3, 3), (5, 3), (5, 5), (3, 5)])
other_polygon = Polygon([(1, 1), (4, 1), (4, 3.5), (1, 3.5)])
intersection = polygon.intersection(other_polygon)
print(intersection.area)
# 0.5

This is much more concise than the version in the accepted answer. You don't have to construct your own Rectangleclass as Shapely already provides the ready ones. It's less error-prone (go figure out the logic in that areafunction). And the code itself is self-explanatory.

这比接受的答案中的版本简洁得多。您不必构建自己的Rectangle类,因为 Shapely 已经提供了现成的类。它不太容易出错(去找出该area函数中的逻辑)。代码本身是不言自明的。



References:
Docs for object.intersection(other)method

参考资料:方法
文档object.intersection(other)