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:
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? 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