Shapely 是基于地理信息系统(GIS)的,对平面特征进行集合理论分析和操作.
Shapely 库安装:
pip install shapely
1. Shapely 基本操作
[1] - 创建点
from shapely.geometry import Point
point = Point(0, 0) # Point((0, 0))
point.area #点的面积
point.length #点的长度
point.bounds #点的边界
输出如:
0.0
0.0
(0.0, 0.0, 0.0, 0.0)
[2] - 创建圆
from shapely.geometry import Point
#创建以(0, 0)为圆心,10为半径的圆
circle = Point(0, 0).buffer(10)
circle.area #圆的面积 313.6548490545939
#圆的面积值小于 pi*r^2, 其原因是:
# buffer方法默认参数resolution为16,
# resolution 的值越大圆越完整.
circle= Point(0, 0).buffer(10, resolution=1000)
circle.area #314.15913616617644
circle= Point(0, 0).buffer(10, resolution=1000000)
circle.area #314.1592653588436
[3] - 创建多边形
from shapely.geometry import Polygon
polygon = Polygon([(0, 1), (0, 2), (0, 3),
(1, 1), (1, 2), (1, 3), (0, 3)])
#Polygon仅能基于有序的点创建多边形,且点的集合必须是闭合的.
#用MultiPoint函数和convex_hull方法创建多边形
from shapely.geometry import MultiPoint
coords = [(0, 1), (1, 2), (1, 4),
(2, 0), (3, 2)] # coords不一定要是闭合点集合
poly = MultiPoint(coords).convex_hull
2. Shapely 集合操作
[1] - 判断点是否在多边形内
from shapely.geometry import Point
from shapely.geometry import Polygon
p1 = Point(0.5, 0.5)
p2 = Point(1.5, 2.5)
poly = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])
#多边形是否包含点
poly.contains(p1)
#True
#点是否在多边形内
p1.within(poly)
#True
#多边形是否包含点
poly.contains(p2)
#False
[2] - 判断多边形的集合操作
from shapely.geometry import Polygon
poly1 = Polygon((0, 0), (0, 1), (1, 1), (1, 0))
poly2 = Polygon([(0.5, 0.5), (1.5,1.5), (2.0, 2.1), (0, 0.2)])
#判断poly1和poly2是否重叠
poly2.intersects(poly1)
#True
#判断poly2是否包含poly1
poly2.contains(poly1)
#False
#判断poly1是否包含poly2
poly1.contains(poly2)
#False