我正在尝试获取没有交集的重叠矩形区域。矩形的可视化如下所示:
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中进行处理?任何帮助将不胜感激。
答案 0 :(得分:0)
如果可以访问“矩形”的角,则可以使用整形模块并使用一些设置操作,例如“差”和“并集”。 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