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

2024-10-01 00:16:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出一个点是否在三维多边形中。我使用了另一个我在网上找到的脚本来处理很多使用光线投射的2D问题。我想知道这是如何改变为三维多边形工作。我不会去看有很多凹坑或洞之类的奇怪的多边形。以下是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

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


Tags: 脚本ifdef多边形maxpoint光线inside
2条回答

我查看了QHull版本(从上面开始)和线性规划解决方案(例如,参见this question)。到目前为止,使用QHull似乎是最好的选择,尽管我可能会错过一些关于scipy.spatialLP的优化。在

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)

在哪里

^{pr2}$

产生:

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

感谢所有的评论。对于任何想找到答案的人来说,我已经找到了一个适用于某些情况(但不适用于复杂情况)的方法。在

我所做的就是利用scipy.spatial.CONVERXHULL公司就像shongololo建议的那样,不过稍微有点扭曲。我正在制作一个三维凸壳的点云,然后添加点我正在检查到一个“新”点云,并作出一个新的三维凸壳。如果它们是相同的,那么我假设它一定在凸壳内部。如果有人能用更有力的方法来做这件事,我还是会很感激的,因为我认为这有点老套。代码如下所示:

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

希望这能帮助将来寻找答案的人!谢谢!在

相关问题 更多 >