python
다각형 겹친 부분의 넓이 구하기 (Python w/ shapely)
jaeha_lee
2024. 1. 8. 01:00
두 다각형의 겹친 부분의 넓이를 구하고 싶을 때, Python에서 shapely라는 라이브러리를 사용하면 간편하다.
아래 코드는 사각형과 육각형의 각 꼭지점 좌표를 알고 있을 때 겹친 부분의 넓이를 구한 코드이다.
from shapely.geometry import Polygon
from shapely.ops import unary_union
def calculate_overlap_area(rectangle, hexagon):
# 다각형 생성
polygon_rect = Polygon(rectangle)
polygon_hex = Polygon(hexagon)
# 겹침 부분 계산
intersection = polygon_rect.intersection(polygon_hex)
# 겹침 부분이 없으면 넓이는 0
if intersection.is_empty:
return 0.0
# 겹침 부분이 있으면 넓이 계산
if intersection.geom_type == 'Polygon':
return intersection.area
elif intersection.geom_type == 'MultiPolygon':
# 여러 개의 다각형이 겹친 경우 넓이를 합산
return sum(poly.area for poly in intersection)
# 예시: 사각형과 육각형의 좌표
rectangle = [(10, 10), (30, 10), (30, 20), (10, 20)]
hexagon = [(20, 15), (25, 10), (30, 15), (27.5, 20), (22.5, 20), (20, 15)]
# 겹친 부분의 넓이 계산
overlap_area = calculate_overlap_area(rectangle, hexagon)
print("겹친 부분의 넓이:", overlap_area)