简体   繁体   English

如何找到重叠矩形的区域

[英]How to find the Area of Overlapping Rectangles

I'm trying to get the area of overlapping rectangles without the intersection. 我正在尝试获取没有交集的重叠矩形区域。 The visualization of the rectangles look like the below: 矩形的可视化如下所示:

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

I'm following the answer from this url , and currently the below code is helpful for me: 我正在跟踪此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)

What is the most efficient way of getting the area of the rectangles (with 3 or more rectangles) and how do I do it in python? 获取矩形(具有3个或更多矩形)面积的最有效方法是什么,如何在python中进行处理? Any help would be appreciated. 任何帮助,将不胜感激。

If you can access the corners of the Rectangles you can use the shapely module and use some set operations like difference and union. 如果可以访问“矩形”的角,则可以使用整形模块并使用一些设置操作,例如“差”和“并集”。 Documentation says that operations are highly optimized. 文档说操作是高度优化的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM