我发现了两种主要的方法来判断一个点是否属于多边形。一种是使用射线跟踪方法,使用here,这是最推荐的答案;另一种是使用matplotlibpath.contains_points
(这对我来说似乎有点模糊)。我要不断地检查很多点。有没有人知道这两个选项中的任何一个比另一个更值得推荐,或者是否还有更好的第三个选项?
更新:
我检查了这两种方法,matplotlib看起来快得多。
from time import time
import numpy as np
import matplotlib.path as mpltPath
# regular polygon for testing
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in np.linspace(0,2*np.pi,lenpoly)[:-1]]
# random points set of points to test
N = 10000
points = zip(np.random.random(N),np.random.random(N))
# Ray tracing
def ray_tracing_method(x,y,poly):
n = len(poly)
inside = False
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
start_time = time()
inside1 = [ray_tracing_method(point[0], point[1], polygon) for point in points]
print "Ray Tracing Elapsed time: " + str(time()-start_time)
# Matplotlib mplPath
start_time = time()
path = mpltPath.Path(polygon)
inside2 = path.contains_points(points)
print "Matplotlib contains_points Elapsed time: " + str(time()-start_time)
这给了我们
Ray Tracing Elapsed time: 0.441395998001
Matplotlib contains_points Elapsed time: 0.00994491577148
用三角形代替100边多边形得到相同的相对差分。我也会检查一下,因为它看起来是一个专门解决这些问题的包
如果速度是您所需要的,并且额外的依赖性不是问题,那么您可能会发现^{} 非常有用(现在在任何平台上都很容易安装)。通过使用
numba @jit
装饰器并将多边形投射到numpy数组,您提出的经典ray_tracing
方法可以很容易地移植到numba
。代码应该如下所示:第一次执行将比任何后续调用花费稍长的时间:
在汇编之后,将减少到:
如果在第一次调用函数时需要速度,那么可以使用
pycc
在模块中预编译代码。将函数存储在src.py中,如下所示:用
python src.py
构建它并运行:在我使用的numba代码中: 'b1(f8,f8,f8[:,:])'
为了用
nopython=True
编译,需要在for loop
之前声明每个变量。在预构建src代码中,行:
用于将函数名及其I/O变量类型、布尔输出
b1
、两个浮点f8
和一个二维浮点数组f8[:,:]
声明为输入。你可以考虑shapely:
从你提到的方法来看,我只使用了第二种方法,
path.contains_points
,它工作得很好。在任何情况下,取决于测试所需的精度,我建议创建一个numpy bool网格,多边形内的所有节点都为True(否则为False)。如果要对许多点进行测试,则速度可能更快(,但请注意,这依赖于您在“像素”公差范围内进行测试):,结果是:
你的测试很好,但它只测量一些特定的情况: 我们有一个有许多顶点的多边形,并且有一个长的点数组来检查多边形内的点。
而且,我想你在测量 多边形内的matplotlib方法与射线方法, 但是 matplotlib优化迭代与简单列表迭代
让我们做N个独立的比较(N对点和多边形)?
结果:
Matplotlib更好,但不是100倍。 现在让我们尝试更简单的多边形。。。
结果:
相关问题 更多 >
编程相关推荐