Python的inpolygon-matplotlib.path.path的示例包含_points()方法?

2024-05-05 02:40:07 发布

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

我一直在寻找一个替代MATLAB的inpolygon()的python,我发现contains_points是一个不错的选择。

但是,这些文档有点赤裸裸,没有指出points期望的数据类型:

contains_points(points, transform=None, radius=0.0)

Returns a bool array which is True if the path contains the corresponding point.

If transform is not None, the path will be transformed before performing the test.

radius allows the path to be made slightly larger or smaller.

我把多边形存储为一个n*2numpy数组(其中n相当大~500)。据我所见,我需要对这些数据调用Path()方法,它似乎工作正常:

poly_path = Path(poly_points)

目前,我还将要测试的点存储为另一个n*2numpy数组(catalog_points)。

也许我的问题就在这里?当我跑的时候:

in_poly = poly_path.contains_points(catalog_points)

我得到一个包含每个值“False”的ndarray,不管我使用的点集是什么(我已经在多边形内的点数组上测试过了)。


Tags: thepathnoneistransform数组be多边形
3条回答

通常在这种情况下,我发现源头是有启发性的。。。

我们可以看到^{}的源接受至少有两个元素的容器。contains_points的源代码比较难理解,因为它调用了C函数^{}。此函数似乎接受一个iterable,该iterable生成长度为2的元素:

>>> from matplotlib import path
>>> p = path.Path([(0,0), (0, 1), (1, 1), (1, 0)])  # square with legs length 1 and bottom left corner at the origin
>>> p.contains_points([(.5, .5)])
array([ True], dtype=bool)

当然,我们也可以使用点的numpy数组:

>>> points = np.array([.5, .5]).reshape(1, 2)
>>> points
array([[ 0.5,  0.5]])
>>> p.contains_points(points)
array([ True], dtype=bool)

为了确认我们并非总是得到True

>>> points = np.array([.5, .5, 1, 1.5]).reshape(2, 2)
>>> points
array([[ 0.5,  0.5],
       [ 1. ,  1.5]])
>>> p.contains_points(points)
array([ True, False], dtype=bool)

我编写此函数是为了返回一个数组,如matlabinpolygon函数中所示。但这将只返回给定多边形内的点。使用此函数无法在多边形的边上找到点。

import numpy as np
from matplotlib import path

def inpolygon(xq, yq, xv, yv):
    shape = xq.shape
    xq = xq.reshape(-1)
    yq = yq.reshape(-1)
    xv = xv.reshape(-1)
    yv = yv.reshape(-1)
    q = [(xq[i], yq[i]) for i in range(xq.shape[0])]
    p = path.Path([(xv[i], yv[i]) for i in range(xv.shape[0])])
    return p.contains_points(q).reshape(shape)

可以将函数调用为:

xv = np.array([0.5,0.2,1.0,0,0.8,0.5])
yv = np.array([1.0,0.1,0.7,0.7,0.1,1])
xq = np.array([0.1,0.5,0.9,0.2,0.4,0.5,0.5,0.9,0.6,0.8,0.7,0.2])
yq = np.array([0.4,0.6,0.9,0.7,0.3,0.8,0.2,0.4,0.4,0.6,0.2,0.6])
print(inpolygon(xq, yq, xv, yv))

^{} documentation这个函数中

returns in indicating if the query points specified by xq and yq are inside or on the edge of the polygon area defined by xv and yv.

确保顶点按要求排列。波纹状顶点的排列方式是绘制三角形而不是矩形。因此,它不会为矩形内的点创建true,而是为三角形内的点创建true。

>>> p = path.Path(np.array([bfp1,bfp2,bfp4,bfp3]))
>>> p
Path([[ 5.53147871  0.78330843]
 [ 1.78330843  5.46852129]
 [ 0.53147871 -3.21669157]
 [-3.21669157  1.46852129]], None)
>>> IsPointInside=np.array([[1,2],[1,9]])
>>> IsPointInside
array([[1, 2],
       [1, 9]])
>>> p.contains_points(IsPointInside)
array([False, False], dtype=bool)
>>> 

如果bfp3和bfp4的顺序正确的话,第一点是正确的。

相关问题 更多 >