numpy 多边形内的点

r3i60tvu  于 2023-04-06  发布在  其他
关注(0)|答案(2)|浏览(258)

我正在寻找一种方法来确定一个特定的点是否在一个多边形内给定其顶点使用NumPy/SciPy。
我在网上找不到。有没有办法用NumPy/SciPy做到这一点?

vcudknz3

vcudknz31#

你有没有考虑过Shapely?只要创建一个多边形,并检查多边形是否包含一个点。

>>> from shapely.geometry import Point
>>> from shapely.geometry.polygon import Polygon

>>> point = Point(0.5, 0.5)
>>> polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])
>>> polygon.contains(point)
True
>>> point2 = Point((10, 10))
>>> polygon.contains(point2)
False
8cdiaqws

8cdiaqws2#

scikit-image(skimage)由与SciPy相同的社区维护,并提供以下方法:https://scikit-image.org/docs/stable/api/skimage.measure.html#skimage.measure.points_in_poly
用法和小例子:

import numpy as np
from skimage.measure import points_in_poly
import matplotlib.pyplot as plt

points = np.array([[0, 0], [1, 0], [1, 1], [0, 1]])
poly = np.array([[0.5, 0.5], [1.5, 0.5], [1.5, 1.5], [0.5, 1.5]])
poly_to_plot = np.vstack([poly, poly[0]])

is_in_poly = points_in_poly(points, poly)
for ii in range(len(points)):
    plt.scatter(*points[ii], color="blue" if is_in_poly[ii] else "black")
plt.plot(*poly_to_plot.T, color="red")

plt.show()

相关问题