Python Shapely 库教程

1. Geometric object

1.1 PointLineStringPolygons

1.1.1 Point(x, y[, z])

# Example
from shapely.geometry import Point
point = Point(0.0, 0.0)

主要属性

  • Point.x-> float
  • Point.y-> float
  • Point.z-> float
  • Point.coords-> iter,返回迭代器类型,为所有点的坐标
    • 可使用 list(Point.coords)
    • 可使用索引 Point.coords[0]

1.1.2 LineString(coordinates)

根据一系列点,按照先后顺序组成的线

主要属性

  • Point.coords-> iterator,返回迭代器类型,为所有点的坐标
from shapely.geometry import LineString
line = LineString([(0, 0), (1, 1)])  # 直接使用 tuple 初始化
line = LineString([Point(0, 0), Point(1, 1)])  # 直接使用 Point 初始化
line = LineString([Point(0, 0), Point(1, 1), (2, 2)])  # 混合初始化

for point in line.coords:  # 遍历 line 的为一个点
    print(point)           # point tuple 类型

1.1.3 LinearRing(coordinates)

LineString 类似,只不过最后一个点会和第一个点连接,形成一个闭环

1.1.4 Polygon(shell[, holes=None])

Polygon 由外环(exterior ring,shell 指定)和内环(interior ring,holes 指定)构成,内环与外环最多只能有一个点的交叉。

注意: 参数 holes 传入类型为 list,每个元素表示一个 hole

主要属性

  • Polygon.exterior-> LinearRing;Polygon 外环

  • Polygon.interiors -> iterator;通过 for 遍历可以得到每个 hole 的环,每个元素为 LinearRing 类型

from shapely.geometry import Polygon, LineString

shell = [(0, 0), (0, 3), (3, 3), (3, 0)]
hole_1 = [(1, 1), (1, 1.5), (1.5, 1)]
hole_2 = [(2, 1), (2, 2), (1, 2)]

polygon_1 = Polygon(shell = shell, holes = [hole_1])  # 传入 holes 参数为 list 类型
polygon_2 = Polygon(shell = shell, holes = [hole_1, hole_2])

print(polygon_2.exterior)    # 返回 LinearRing 类型
print(polygon_2.interiors)   # 返回 迭代器 类型
for ring in polygon_2.interiors:  # 遍历
    print(ring)    # 每个 ring 为 LinearRing 类型
其他相关方法

shapely.geometry.box(minx, miny, maxx, maxy, ccw=True):矩形

  • 参数:ccw 设置 4 个顶点的顺序,ccw=True 表示逆时针顺序(counter-clockwise order )

shapely.geometry.polygon.orient(polygon, sign=1.0):对 polygon 调整顶点的顺序并返回:

  • 参数:sign=1.0 表示外环逆时针(counter-clockwise)顺序,内环(holes)顺时针(clockwise)顺序

1.1.5 Single-Part Geometry 通用方法和属性

以下方法只有 PointLineString, 和 LinearRing 的 Geometry 类型才有

object.coords-> iterator;每个元素为二元或三元 tuple

object.xy-> tuple

  • 返回一个二元 tuple,tuple 中的每个元素为 array.array 数据类型

  • 第一个 array.array 为 x 坐标的合集

  • 第一个 array.array 为 y 坐标的合集

1.2 Collections

1.2.1 MultiPoint

1.2.2 MultiLineString

1.2.3 MultiPolygon

1.2.4 Collections 的通用方法和属性

multi_object.geoms-> iterator,遍历每个成员

multi_object[0]: 通过索引,访问某个成员

1.3 通用属性和方法

1.3.1 基本信息

object.area:面积

object.length:长度

  • A Point has zero area and zero length.

  • A LineString has zero area and non-zero length.

object.bounds:a bound of (minx, miny, maxx, maxy)

object.minimum_clearance

  • 如果没有 minimum clearance 存在,比如说同一个 point, 将会返回 math.infinity

object.geom_type:Geometry Type

object.distance(other):最小距离

object.hausdorff_distance(other) Hausdorff 距离,wikipedia

object.representative_point():代表点,一定在几何的内部;大致原理:site

Linear Referencing Methods

2.Predicates and Relationships

2.1 Unary Predicates

object.has_z: -> bool;是否有 z 坐标

object.is_empty: 是否含有成员(即,是否为空)

object.is_ring: 是否是一个闭环

object.is_ccw:是否是逆时针(counter-clockwise order)

  • 只用于 LinearRing 对象

object.is_simple

object.is_valid

  • 关于几何对象的 simple 和 valid 的定义参考官方文档

2.2 Binary Predicates 几何关系

A. Equal

object.__eq__(other):geometry 类别和成员是否相等

  • 等价于 ==

object.equals(other):集合意义上是否相等

object.almost_equals(other[, decimal=6])

from shapely.geometry import LineString

# a, b, c, d 表示同一条线
a = LineString([(0, 0), (1, 1)])
b = LineString([(0, 0), (0.5, 0.5), (1, 1)])
c = LineString([(0, 0), (0, 0), (1, 1)])
d = LineString([(0, 0), (0, 0), (1, 1)])

print(a.equals(b), a.equals(c), c.equals(d))
print(a.__eq__(b), a.__eq__(c), c.__eq__(d))
print(a == b, a == c, c == d)
# Output:  True True True
# Output:  False False True
# Output:  False False True

B. contains 和 covers

判断点是否在多边形内的算法:Point in polygon, Wikipedia

object.contains(other):True 表示 other没有点存在 object外部,并且,other 中至少一个 interior 点存在 object 的 interior

  • 等价于 other.within(object)

object.within(other)

object.covers(other):True 表示 other 中的所有点都在 object 的 boundary 或 interior

  • .contains() 不同的是,.covers() 没有对内部点的要求

object.covered_by(other):等价于 other.covers(object)

实例:contains (within) v.s. covers (covered_by)

poly = Polygon([(0, 0), (0, 2), (2, 2), (2, 0)])  # a square
line_1 = LineString([(0, 0), (0, 2)])  # an edge of the square
line_2 = LineString([(0, 0), (2, 2)])  # a diagonal of the square
point = Point((0, 0))  # vertex of the square
# 
print(line_1.contains(point), point.within(line_1))    # False False
print(line_1.covers(point), point.covered_by(line_1))  # True True
# 
print(poly.contains(line_1), line_1.within(poly))     # False False
print(poly.covers(line_1), line_1.covered_by(poly))   # True True
# 
print(poly.contains(line_2), line_2.within(poly))    # True True
print(poly.covers(line_2), line_2.covered_by(poly))  # True True

C.

object.crosses(other)

object.overlaps(other)

object.disjoint(other):True 表示 object 中的所有点(boundary 和 interior)都other 的相交

  • object.intersects(other) 的逆运算

object.intersects(other):True 表示 object 中的存在点(boundary 或 interior)与 other 中的相交,即 objectother 存在至少一个共同点

object.touches(other)objectother 存在至少一个共同点,并且 interior 点不相交

3. Spatial Analysis Methods 空间分析方法

3.1 Set-theoretic Methods 集合论方法

object.boundary:边界

  • the boundary of a polygon is a line. 如果是有 holes 的 polygon,则返回 MultiLineString
  • the boundary of a line is a collection of points
  • the boundary of a point is an empty (null) collection.

object.centroid:质心,可能在几何外

object.difference(other):差集

  • 等价于 object - other

  • object.difference(other) 不等于 other.difference(object)

object.intersection(other):交集

  • 等价于object & other

object.symmetric_difference(other):对称差集

  • 两个差集的并集

  • 等价于 other.symmetric_difference(object)

  • 等价于object ^ other

object.union(other):并集

  • 等价于object | other

3.2 Constructive Methods 构造方法

(1) object.buffer()

object.buffer(distance, resolution=16, cap_style=1, join_style=1, mitre_limit=5.0, single_sided=False)

主要参数

  • cap_style:边界倒角倒角类型
    • 1 (round), 2 (flat), 3 (square)
  • join_style:连段连接处倒角类型
    • 1 (round), 2 (mitre), 3 (square)
  • single_sided (bool):是否单边
    • a positive distance indicates the left-hand side
    • a negative distance indicates the right-hand side

object.convex_hull

object.envelope:返回一个最小矩形,边与坐标平行

object.minimum_rotated_rectangle

object.parallel_offset(distance, side, resolution=16, join_style=1, mitre_limit=5.0)

4 Interoperation

4.1 Well-Known Formats

Well Known Text (WKT) 格式或 Well Known Binary (WKB),一种表示几何对象的方法;wikipedia

object.wktobject.wkb:返回几何对象的 WKT 格式或 WKB 格式的字符串

shapely.wkt.dumps(object)shapely.wkb.dumps(object)

shapely.wkt.loads(wkt)shapely.wkb.loads(wkb)

4.2 Numpy and Python Arrays

利用 numpy.asarray 方法,将坐标序列 (Point, LinearRing, LineString) 转换为 numpy.ndarray 数组

import numpy as np
from shapely.geometry import Point, LineString, Polygon

point = Point((0, 0)).coords
line = LineString([(0, 0), (2, 0), (2, 2)]).coords
polygon = Polygon([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]])
polygon_exterior = polygon.exterior.coords    # polygon 的外边界

print(np.asarray(point))
print(np.asarray(line))
print(np.asarray(polygon_exterior))

利用 shapely.geometry.asShape() 族或 shapely.geometry.shape()方法,将 numpy.ndarray 数组转换为 shapely.geometry 对象

# shapely.geometry.asShape() 方法
from shapely.geometry import asPoint
from shapely.geometry import asMultiPoint
from shapely.geometry import asLineString
from shapely.geometry import asPolygon
# shapely.geometry.shape() 方法
from shapely.geometry import shape

实例

from shapely.geometry import asPoint, asLineString, shape

point = asPoint(array([0.0, 0.0]))
line = asLineString(array([[1.0, 2.0], [3.0, 4.0]]))

point = shape({"type": "Point", "coordinates": (0.0, 0.0)})

5. 技巧

5.1 修复 invalid 的 geometry 对象

方法一: 创建 distance=0 的 buffer,参考 site

geometry.buffer(0)

方法二: shapely.validation 模块中,make_valid() 方法

from shapely.validation import make_valid
coords = [(0, 2), (0, 1), (2, 0), (0, 0), (0, 2)]
poly_1 = Polygon(coords)
poly_2 = make_valid(poly_1)

参考文献

The Shapely User Manual, site

Shapely and geometric objects, Automating GIS-processes 2021, site

Point in polygon, Wikipedia, site

posted @ 2022-06-03 00:36  veager  阅读(4944)  评论(0)    收藏  举报