-1

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)
MattDMo
  • 100,794
  • 21
  • 241
  • 231
AIpython
  • 3
  • 2
  • `intersection` isn't going to work for your needs. That simply computes the overlapping regions of the rectangles without regard to whether their edges align. – Woodford Feb 01 '23 at 18:24
  • thanks for your advice, which command from shapely should I use? – AIpython Feb 01 '23 at 19:00
  • If one rectangle contains the other, the outlines don't touch !? –  Feb 01 '23 at 19:26
  • Yes, the edges of the rectangles touch, in my case two edges of the small rectangle touch with two edges of the large rectangle. What I want is to find the sum of the lengths of the edges of the small rectangle that touch the edges of the large rectangle. – AIpython Feb 01 '23 at 19:35

2 Answers2

0

I solved my problem without shapely. In case someone has the same problem, here is the code:

big_rect = [(0,0), (0,600), (800,600), (800,0), (0,0)]
small_rect = [(0,199), (0,399), (200,399), (200,199), (0,199)]

def calc_touch_length(big_rect, small_rect):
    touch_length = 0
    for i in range(len(small_rect) - 1):
        p1 = small_rect[i]
        p2 = small_rect[i + 1]
        if p1[0] == 0 and p2[0] == 0:
            touch_length += abs(p2[1] - p1[1])
        elif p1[1] == 0 and p2[1] == 0:
            touch_length += abs(p2[0] - p1[0])
    return touch_length

print(calc_touch_length(big_rect, small_rect))
AIpython
  • 3
  • 2
0

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)
Michael Delgado
  • 13,789
  • 3
  • 29
  • 54