在python中查找点是否为3D多边形

时间:2015-03-27 23:15:40

标签: python 3d polygons point-in-polygon

我试图找出一个点是否在3D多边形中。我曾使用过我在网上找到的另一个脚本来处理使用光线投射的许多2D问题。我想知道如何将其更改为适用于3D多边形。我不会看到有很多凹面或洞或任何东西的奇怪多边形。这是python中的2D实现:

def point_inside_polygon(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:
                        xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xinters:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside

任何帮助将不胜感激!谢谢。

3 个答案:

答案 0 :(得分:2)

提出了类似的问题here,但重点是效率

@Brian@fatalaccidents在这里建议的scipy.spatial.ConvexHull方法有效,但是如果您需要检查多个问题,则非常慢

most efficient solution也来自scipy.spatial,但是利用了Delaunay镶嵌方法:

from scipy.spatial import Delaunay

Delaunay(poly).find_simplex(point) >= 0  # True if point lies within poly

之所以可行,是因为如果该点不在任何简单形式(即不在三角测量之外)中,则-1返回.find_simplex(point)。 (注意:它可以在N个维度上使用,而不仅是2 / 3D。)


性能比较

首先一个点

import numpy
from scipy.spatial import ConvexHull, Delaunay

def in_poly_hull_single(poly, point):
    hull = ConvexHull(poly)
    new_hull = ConvexHull(np.concatenate((poly, [point])))
    return np.array_equal(new_hull.vertices, hull.vertices)

poly = np.random.rand(65, 3)
point = np.random.rand(3)

%timeit in_poly_hull_single(poly, point)
%timeit Delaunay(poly).find_simplex(point) >= 0

结果:

2.63 ms ± 280 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
1.49 ms ± 153 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

因此Delaunay方法更快。但这取决于多边形的大小!我发现,对于包含超过65个点的多边形,Delaunay方法变得越来越慢,而ConvexHull方法的速度几乎保持不变。

多个点

def in_poly_hull_multi(poly, points):
    hull = ConvexHull(poly)
    res = []
    for p in points:
        new_hull = ConvexHull(np.concatenate((poly, [p])))
        res.append(np.array_equal(new_hull.vertices, hull.vertices))
    return res

points = np.random.rand(10000, 3)

%timeit in_poly_hull_multi(poly, points)
%timeit Delaunay(poly).find_simplex(points) >= 0

结果:

155 ms ± 9.42 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
1.81 ms ± 106 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

因此Delaunay极大地提高了速度;更不用说我们要等待1万点以上的时间。在这种情况下,多边形尺寸不会再有太大的影响。


总而言之,Delaunay不仅速度更快,而且代码也非常简洁。

答案 1 :(得分:1)

感谢所有评论过的人。对于那些正在寻找答案的人,我发现一个适用于某些情况(但不是复杂的情况)。

我正在做的是使用像shongololo建议的scipy.spatial.ConvexHull,但稍微扭曲一下。我正在制作点云的3D凸包,然后将我检查的点添加到“新”点云并制作新的3D凸包。如果它们是相同的,那么我假设它必须在凸包内。如果有人有更强有力的方法,我仍然会感激,因为我认为这有点像hackish。代码如下所示:

from scipy.spatial import ConvexHull

def pnt_in_pointcloud(points, new_pt):
    hull = ConvexHull(points)
    new_pts = points + new_pt
    new_hull = ConvexHull(new_pts)
    if hull == new_hull: 
        return True
    else:
        return False

希望这可以帮助将来寻找答案的人!谢谢!

答案 2 :(得分:1)

我查看了QHull版本(来自上面)和线性编程解决方案(例如参见this question)。到目前为止,使用QHull似乎是最好的选择,尽管我可能会错过scipy.spatial LP的一些优化。

import numpy
import numpy.random
from numpy import zeros, ones, arange, asarray, concatenate
from scipy.optimize import linprog

from scipy.spatial import ConvexHull

def pnt_in_cvex_hull_1(hull, pnt):
    '''
    Checks if `pnt` is inside the convex hull.
    `hull` -- a QHull ConvexHull object
    `pnt` -- point array of shape (3,)
    '''
    new_hull = ConvexHull(concatenate((hull.points, [pnt])))
    if numpy.array_equal(new_hull.vertices, hull.vertices): 
        return True
    return False


def pnt_in_cvex_hull_2(hull_points, pnt):
    '''
    Given a set of points that defines a convex hull, uses simplex LP to determine
    whether point lies within hull.
    `hull_points` -- (N, 3) array of points defining the hull
    `pnt` -- point array of shape (3,)
    '''
    N = hull_points.shape[0]
    c = ones(N)
    A_eq = concatenate((hull_points, ones((N,1))), 1).T   # rows are x, y, z, 1
    b_eq = concatenate((pnt, (1,)))
    result = linprog(c, A_eq=A_eq, b_eq=b_eq)
    if result.success and c.dot(result.x) == 1.:
        return True
    return False


points = numpy.random.rand(8, 3)
hull = ConvexHull(points, incremental=True)
hull_points = hull.points[hull.vertices, :]
new_points = 1. * numpy.random.rand(1000, 3)

,其中

%%time
in_hull_1 = asarray([pnt_in_cvex_hull_1(hull, pnt) for pnt in new_points], dtype=bool)

产生

CPU times: user 268 ms, sys: 4 ms, total: 272 ms
Wall time: 268 ms

%%time
in_hull_2 = asarray([pnt_in_cvex_hull_2(hull_points, pnt) for pnt in new_points], dtype=bool)

产生

CPU times: user 3.83 s, sys: 16 ms, total: 3.85 s
Wall time: 3.85 s