Skip to content

Instantly share code, notes, and snippets.

@baojie
Created March 20, 2013 03:48
Show Gist options
  • Save baojie/5202161 to your computer and use it in GitHub Desktop.
Save baojie/5202161 to your computer and use it in GitHub Desktop.
Shapely is a BSD-licensed Python package for manipulation and analysis of planar geometric objects. https://github.com/sgillies/shapely
from shapely.geometry import Point
point = Point(0, 0)
print point.geom_type
# OUT: Point
print point.area
# OUT: 0.0
patch = point.buffer(10)
print patch.bounds
# OUT: (-10.0, -10.0, 10.0, 10.0)
print list(point.coords)
# OUT: [(0.0, 0.0)]
from shapely.geometry import LineString
line = LineString([(0, 0), (1, 1)])
print line.length
# OUT: 1.41421356237
from shapely.geometry.polygon import LinearRing
ring = LinearRing([(0, 0), (1, 1), (1, 0)])
ring.length
# OUT: 3.414213562373095
from shapely.geometry import Polygon
polygon = Polygon([(0, 0), (1, 1), (1, 0)])
print polygon.area
# OUT: 0.5
print list(polygon.exterior.coords)
# OUT: [(0.0, 0.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)]
print list(polygon.interiors)
# OUT: []
from shapely.geometry import box
b = box(0.0, 0.0, 1.0, 1.0)
print list(b.exterior.coords)
# OUT: [(1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0), (1.0, 0.0)]
Point(0, 0, 0).has_z
# OUT: True
# counter-clockwise
LinearRing([(1,0), (1,1), (0,0)]).is_ccw
# OUT: True
LinearRing([(0, 0), (1, 1), (1, -1)]).is_ring
# OUT: True
coords = [(0, 0), (1, 1)]
LineString(coords).contains(Point(0.5, 0.5))
# OUT: True
Point(0.5, 0.5).within(LineString(coords))
# OUT: True
LineString(coords).crosses(LineString([(0, 1), (1, 0)]))
# OUT: True
Point(0, 0).disjoint(Point(1, 1))
# OUT: True
a = LineString([(0, 0), (1, 1)])
b = LineString([(1, 1), (2, 2)])
a.touches(b)
# OUT: True
a = Point(2, 2)
b = Polygon([[1, 1], [1, 3], [3, 3], [3, 1]])
c = Polygon([[0, 0], [0, 4], [4, 4], [4, 0]])
d = Point(-1, -1)
d < c
# OUT: True
class Within(object):
def __init__(self, o):
self.o = o
def __lt__(self, other):
return self.o.within(other.o)
from shapely.geometry import asShape
Within(d) < Within(c)
# OUT: False
line = LineString([(0, 0), (1, 1), (0, 2), (2, 2), (3, 1), (1, 0)])
dilated = line.buffer(0.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment