Search code examples
pythoncomputational-geometryshapely

Touch edges two rectangles with shapely


I have two rectangles. One rectangle contains the other. I want to find the length of the segments where they touch each other.

I have tried this code but the result is 798 which is wrong because the result I am looking for is 399.

from shapely.geometry import Polygon

big_rect = Polygon([(0,0), (0,600), (800,600), (800,0)])
small_rect = Polygon([(0,0), (0,199), (200,199), (200,0)])
intersection = big_rect.intersection(small_rect)
touch_length = intersection.boundary.length
print(touch_length)

Solution

  • You could do this using shapely by first finding the boundaries of each rectangle, then computing the intersection to get the intersecting line segment:

    from shapely.geometry import Polygon
    
    big_rect = Polygon([(0,0), (0,600), (800,600), (800,0)])
    small_rect = Polygon([(0,0), (0,199), (200,199), (200,0)])
    
    intersection = big_rect.boundary.intersection(
        small_rect.boundary
    )
    
    touch_length = intersection.length
    print(touch_length)