8

Say, if I have two polygons, their name and coordinates are (in Python):

p:[(1,1),(2,2),(4,2),(3,1)]
q:[(1.5,2),(3,5),(5,4),(3.5,1)]

In our human brain, it is easy to know that these two polygons are intersected and calculate the intersection area coordinates, but I want to let our machine know how to calculate the intersection area's coordinates. Basically, I want to know if there is a simple and clear algorithm for this job, if there is already a Python library could do this, it will be perfect.

hellomynameisA
  • 546
  • 1
  • 7
  • 28
Zhou XF
  • 163
  • 1
  • 2
  • 11

2 Answers2

23
from shapely.geometry import Polygon

p = Polygon([(1,1),(2,2),(4,2),(3,1)])
q = Polygon([(1.5,2),(3,5),(5,4),(3.5,1)])
print(p.intersects(q))  # True
print(p.intersection(q).area)  # 1.0
x = p.intersection(q)
print(x) #POLYGON ((1.833333333333333 1.833333333333333, 2 2, 4 2, 3.166666666666667 1.166666666666667, 1.833333333333333 1.833333333333333))

shapely user manual: https://shapely.readthedocs.io/en/stable/manual.html

DarrylG
  • 16,732
  • 2
  • 17
  • 23
  • thanks for your answer, your method achieves the first goal that I raise,but it is coordinates of the intersection area that I wanted, not the area,is it possible to do this with shapely? – Zhou XF Sep 11 '19 at 09:23
  • 1
    Couldn't you create a new polgyon from the intersection result and find the area of that? – ZWang Jul 02 '20 at 04:05
  • For future readers, see [this answer](https://stackoverflow.com/a/17849389/13809128) for how to install shapely together with GEOS. Note that installing shapely via pip does not automatically install GEOS. – mhdadk Aug 07 '21 at 18:35
1
from turfpy.transformation import intersect
from turfpy.measurement import area
from geojson import Feature
f = Feature(geometry={"coordinates": [
[[-122.801742, 45.48565], [-122.801742, 45.60491],
[-122.584762, 45.60491], [-122.584762, 45.48565],
[-122.801742, 45.48565]]], "type": "Polygon"})
b = Feature(geometry={"coordinates": [
[[-122.520217, 45.535693], [-122.64038, 45.553967],
[-122.720031, 45.526554], [-122.669906, 45.507309],
[-122.723464, 45.446643], [-122.532577, 45.408574],
[-122.487258, 45.477466], [-122.520217, 45.535693]
]], "type": "Polygon"})
inter = intersect([f, b])
area(inter)

You can use Turfpy which is a library that contains various functionalities Turfpy