在 Python 中,检查点是否在多边形内的最快方法是什么?

pythonmatplotlibserver side programmingprogramming更新于 2024/9/21 19:24:17

首先,我们将使用 mplPath.Path 方法创建一个多边形,并使用 poly_path.contains_point 方法检查给定点是否在多边形内。

步骤

  • 创建一个点列表以构成多边形。

  • 使用 mplPath.Path() 使用给定的顶点和代码创建新路径。

  • 使用 contains_point() 方法检查点 (200, 100) 是否存在于多边形中。返回 (闭合) 路径是否包含给定点。=> True

  • 使用 contains_point() 方法检查点 (1200, 1000) 是否存在于多边形中。返回(封闭)路径是否包含给定点。=> False

示例

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

相关文章


有用资源