如何找到重叠矩形的面积

How to find the Area of Overlapping Rectangles

我正在尝试获取没有交集的重叠矩形的面积。矩形的可视化如下所示:

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAA--------------BBB
AAAAAAAAAAAAAAAA--------------BBB
AAAAAAAAAAAAAAAA--------------BBB
AAAAAAAAAAAAAAAA--------------BBB
                BBBBBBBBBBBBBBBBB
                BBBBBBBBBBBBBBBBB
                BBBBBBBBBBBBBBBBB
                BBBBBB-----------CCCCCCCC
                BBBBBB-----------CCCCCCCC
                BBBBBB-----------CCCCCCCC
                      CCCCCCCCCCCCCCCCCCC
                      CCCCCCCCCCCCCCCCCCC
                      CCCCCCCCCCCCCCCCCCC
                      CCCCCCCCCCCCCCCCCCC

我正在关注这个 url 的答案,目前以下代码对我有帮助:

import numpy as np

A = np.zeros((100, 100))
B = np.zeros((100, 100))

A[rect1.top : rect1.bottom,  rect1.left : rect1.right] = 1
B[rect2.top : rect2.bottom,  rect2.left : rect2.right] = 1

area_of_union     = np.sum((A + B) > 0)
area_of_intersect = np.sum((A + B) > 1)

获取矩形(具有 3 个或更多矩形)面积的最有效方法是什么?我如何在 python 中实现?任何帮助将不胜感激。

如果您可以访问矩形的角,则可以使用 shapely 模块并使用一些集合运算,例如差集和并集。 Documentation 表示操作已高度优化。

from shapely.geometry import Polygon, Point

# define rectangles as polygons using their border points
A = Polygon(((0, 0), (2, 0), (2, 2), (0, 2)))

B = Polygon(((-1, -1), (-1, 1), (1, 1), (1, -1)))

C = Polygon(((0, 0), (-2, 0), (-2, -2), (0, -2)))

print(A.area)  # 4.0
print(B.area)  # 4.0
print(C.area)  # 4.0

b_without_a = B.difference(A)
b_without_c = B.difference(C)

print(b_without_a.area)  # 3.0
print(b_without_c.area)  # 3.0

total = b_without_a.intersection(b_without_c)

print(total.area)  # 2.0