Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Shapely for subtracting two polygons

I am not really sure how to explain this but I have 2 polygons, Polygon1 and Polygon2. These polygons overlapped with each other. How to do I get Polygon2 using Shapely without the P from Polygon1.

like image 279
simple guy Avatar asked Dec 22 '22 17:12

simple guy


1 Answers

You are looking for a difference. In Shapely you can calculate it either by using a difference method or by simply subtracting* one polygon from another:

from shapely.geometry import Polygon

polygon1 = Polygon([(0.5, -0.866025), (1, 0), (0.5, 0.866025), (-0.5, 0.866025), (-1, 0), (-0.5, -0.866025)])
polygon2 = Polygon([(1, -0.866025), (1.866025, 0), (1, 0.866025), (0.133975, 0)])

enter image description here

difference = polygon2.difference(polygon1)  # or difference = polygon2 - polygon1

enter image description here

See docs for more set-theoretic methods.


*This feature is not documented. See issue on GitHub: Document set-like properties.

like image 179
Georgy Avatar answered Jan 09 '23 07:01

Georgy