多边形内部点

12

我正在寻找一种使用NumPy/SciPy确定一个特定点是否在给定顶点的多边形内的方法。

我没有在网上找到这样的方法。使用NumPy/SciPy有没有办法实现这个目标?


你已经在这里问过这个问题。如果你对我给出的答案不满意,应该取消采纳并发表评论解释原因,而不是开另一个问题。 - ali_m
不是同一个问题,上一个是关于裁剪的,这个是关于点在多边形内的。 - High schooler
基本的根本问题是相同的 - 您的“作物”区域是一个多边形,您想索引落在多边形内的点。Arkottke和我的回答都解决了这个问题。 - ali_m
不同的问题,然而。 - High schooler
2个回答

16

你有没有考虑过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

哦,有趣!虽然我希望numpy/scipy能够做这件事,而无需安装新模块。顺便问一下:您知道有什么工具可以允许我在图像上绘制顶点吗? - High schooler
@Highschooler 我会在matplotlib图形上使用图像作为背景,然后使用event handling来选择点。 - arkottke
Shapely不幸的是没有pip pip installs shapely :( - user1767754
1
@user1767754,现在它可以在Windows上使用了,只是之前好像不行。https://pypi.org/project/Shapely/ - Yuri Feldman

0

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()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接