Reputation: 147
I am having trouble to calculate the overlap area of two rectangles using Python.
The rectangle may be sloped.
The input is eight values: (left_top, right_top, left_bottom, right_bottom)
and the function should return the overlapping area.
Is there a possible solution? Thanks you so much if you can help! :)
Upvotes: 1
Views: 660
Reputation: 1
As mentioned by MBo in his answer, this can be easily achieved using Shapely and Python:
from shapely.geometry import Polygon
def get_overlap_polygon(rect1_coords, rect2_coords):
rect1 = Polygon(rect1_coords)
rect2 = Polygon(rect2_coords)
poly_intersection = rect1.intersection(rect2)
return poly_intersection.exterior.coords, poly_intersection.area
Sample inputs: rect1_coords = [(1.1408563820557887, 0.20116376126988017), (0.7988362387301199, 1.1408563820557887), (-0.14085638205578857, 0.7988362387301199), (0.20116376126988014, -0.14085638205578854), (1.1408563820557887, 0.20116376126988017)] rect2_coords = [(1.2044160264027588, 0.4383715832837807), (0.5616284167162194, 1.2044160264027588), (-0.20441602640275877, 0.5616284167162194), (0.43837158328378056, -0.20441602640275866), (1.2044160264027588, 0.4383715832837807)]
Output:
Upvotes: 0
Reputation: 80187
You can calculate resulting intersection using algorithm from O'Rourke book "Computational Geometry in C" - C code is available, file convconv
.
Algorithm outline is here
Also you can use libraries like Shapely - arbitrary found example, or Clipper (has third party Pytgon modules)
Upvotes: 1