本文参考
文档1,
文档2
有两种方法,将分别做出说明。
1、使用matplotlib.path库
步骤:
- 创建多边形点
- matplotlib.path生成多边形路径
- 判断点是否在多边形内
示例代码为:
import matplotlib.path as mplPath
import numpy as np
poly = [190, 50, 500, 310]
poly_path = mplPath.Path(np.array([[190, 50],
[50, 500],
[500, 310],
[310, 190]]))
point = (200, 100)
print(point, " is in polygon: ", poly_path.contains_point(point))
point = (1200, 1000)
print(point, " is in polygon: ", poly_path.contains_point(point))
输出为: (200, 100) is in polygon: True (1200, 1000) is in polygon: False
如果是多个点,那么point是N,2的numpy ndarray即可。
2、使用shapely库
示例:
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
point = Point(0.5, 0.5)
polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])
print(polygon.contains(point))
但shapely库只能用在linux系统
对比速度:
import matplotlib.path as mplPath
import numpy as np
import time
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
poly_path = mplPath.Path(np.array([[190, 50],[50, 500],[500, 310],[310, 190]]))
point1 = (200, 100)
point2 = (1200, 1000)
print(point1, " is in polygon: ", poly_path.contains_point(point1))
print(point2, " is in polygon: ", poly_path.contains_point(point2))
start = time.time()
for i in range(1000):
poly_path.contains_point(point1)
duration = time.time()-start
print('total time',duration)
point1 = Point(200, 100)
point2 = Point(1200,1000)
polygon = Polygon([[190, 50],[50, 500],[500, 310],[310, 190]])
print(polygon.contains(point1))
print(polygon.contains(point2))
start = time.time()
for i in range(1000):
polygon.contains(point1)
duration = time.time()-start
print('total time',duration)
结果: 第二种方法速度慢,当多边形点和要检查的点增多时,速度会有更多影响,所以要使用第一种。
更多快速的方法参考我提供的链接。
|