High schooler
High schooler

Reputation: 1680

Point inside polygon

I'm looking for a way to determine whether a particular point is within a polygon given its vertices using NumPy/SciPy.

I haven't been able to find one online. Is there even a way to do this using NumPy/SciPy?

Upvotes: 12

Views: 9210

Answers (2)

ntjess
ntjess

Reputation: 1460

scikit-image (skimage) is maintained by the same community as SciPy, and has this method available: https://scikit-image.org/docs/stable/api/skimage.measure.html#skimage.measure.points_in_poly

Usage and small example:

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

Upvotes: 0

arkottke
arkottke

Reputation: 567

Have you considered Shapely? Just create a Polygon and check if polygon contains a point.

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

Upvotes: 16

Related Questions