What's the fastest way of checking if a point is inside a polygon in Python?

PythonMatplotlibServer Side ProgrammingProgramming

First, we will create a polygon using the mplPath.Path method and to check whether a given point is in the polygon or not, we will use the method, poly_path.contains_point.

Steps

  • Create a list of points to make the polygon.

  • Create a new path with the given vertices and codes, using mplPath.Path().

  • Check if point (200, 100) exists in the polygon or not, using contains_point() method. Return whether the (closed) path contains the given point. => True

  • Check if point (1200, 1000) exists in the polygon or not, using contains_point() method. Return whether the (closed) path contains the given point. => False

Example

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

Output

(200, 100) is in polygon: True
(1200, 1000) is in polygon: False
raja
Published on 16-Mar-2021 10:26:17
Advertisements