(个人微信号361318358)
前段时间有朋友问破解后的ArcGIS做缓冲区时总是失败,想到Python做缓冲区分析应该并不复杂,之前就看到过Shapely这个工具在GIS分析方面的例子,所以查下相关资料,写一个入门的用shapely进行缓冲区分析的小例子。
基本概念
缓冲区分析是根据指定的距离,在点、线、面几何对象周围建立一定宽度的区域的分析方法。
注意:Manipulation and analysis of geometric objects in the Cartesian plane
Shapely
shapely是在笛卡尔平面对几何对象进行操作和分析的Python工具包。它基于应用广泛的GEOS和JTS库。
Shapely is a BSD-licensed Python package for manipulation and analysis of planar geometric objects. It is based on the widely deployed GEOS (the engine of PostGIS) and JTS (from which GEOS is ported) libraries.
用shapely生成缓冲区时,主要使用object.buffer(distance,...)语法。
在开始示例之前,先引入点线面类型。
from shapely.geometry import Point
from shapely.geometry import LineString
from shapely.geometry import MultiPolygon
点缓冲区
# 定义两个点
point_1 = Point(1, 1)
point_2 = Point(2, 1.2)
# 两个点以指定的缓冲距离为半径生成圆形区域
a = point_1.buffer(2)
b = point_2.buffer(1.5)
相交与合并操作
inter = a.intersection(b)
union = a.union(b)
bufferPlt(inter,union,'intersection','union')
裁剪操作
diff1 = a.difference(b)
diff2 = b.difference(a)
bufferPlt(diff1,diff2,'difference(a-b)','difference(b-a)')
线缓冲区
线的缓冲区是沿线对象的法线方向,分别向线对象的两侧平移一定的距离而得到两条线,并与在线端点处形成的光滑曲线(或平头)接合形成的封闭区域。
# 定义两条线段
line_1 = LineString([(0.1, 0.1), (2, 3)])
line_2 = LineString([(0.2, 0.4), (3.5, 2.5)])
# 生成缓冲区
a = line_1.buffer(0.5)
b = line_2.buffer(0.5)
相交与合并操作
inter = a.intersection(b)
union = a.union(b)
bufferPlt(inter,union,'intersection','union')
裁剪操作
diff = a.difference(b)
fig = pyplot.figure(1, figsize=(5,5),dpi=90)
ax = fig.add_subplot(111)
for polygon in diff:
patch = PolygonPatch(polygon, alpha=0.5, zorder=2)
ax.add_patch(patch)
x_a,y_a = a.boundary.xy
x_b,y_b = b.boundary.xy
ax.plot(x_a,y_a,'b')
ax.plot(x_b,y_b,'g')
ax.set_title('difference')
面缓冲区
用shapely生成面缓冲区的语法和点线类似,其实生成的点线缓冲区对象本身就是Polygon类型。
网友评论