1

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.

Example

Is there a possible solution? Thanks you so much if you can help! :)

IvanEFan
  • 117
  • 2
  • 10
  • There might be a possible solution, but first we need to see yours. What's your proposal, what code have you tried that didn't work? – Shinra tensei Aug 12 '21 at 08:49
  • I have tried using PIL to draw transparent rectangles and calculate the darker color and it works, but it will cause performance issue. I have no idea how to implement it using pure calculation. – IvanEFan Aug 12 '21 at 09:03

2 Answers2

1

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)

MBo
  • 77,366
  • 5
  • 53
  • 86
0

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:

enter image description here