Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What's the fastest way of checking if a point is inside a polygon in Python?
Checking if a point is inside a polygon is a common computational geometry problem. Python offers several approaches, with matplotlib's Path class being one of the fastest and most reliable methods for this task.
Using matplotlib.path for Point-in-Polygon Testing
The matplotlib library provides an efficient implementation through the mplPath.Path class, which uses optimized algorithms for point-in-polygon testing.
Steps
Create a list of points to define the polygon vertices.
Create a path object using
mplPath.Path()with the polygon coordinates.Use the
contains_point()method to check if a point lies inside the polygon.
Example
import matplotlib.path as mplPath
import numpy as np
# Define polygon vertices (triangle-like shape)
polygon_vertices = np.array([[190, 50],
[50, 500],
[500, 310],
[310, 190]])
poly_path = mplPath.Path(polygon_vertices)
# Test points
point1 = (200, 100)
point2 = (1200, 1000)
print(point1, "is in polygon:", poly_path.contains_point(point1))
print(point2, "is in polygon:", poly_path.contains_point(point2))
(200, 100) is in polygon: True (1200, 1000) is in polygon: False
Testing Multiple Points Efficiently
For checking multiple points at once, use contains_points() method which is more efficient than individual calls ?
import matplotlib.path as mplPath
import numpy as np
# Define polygon
polygon_vertices = np.array([[0, 0], [10, 0], [10, 10], [0, 10]])
poly_path = mplPath.Path(polygon_vertices)
# Multiple test points
test_points = np.array([[5, 5], [15, 15], [2, 8], [12, 3]])
results = poly_path.contains_points(test_points)
for i, point in enumerate(test_points):
print(f"Point {point} is in polygon: {results[i]}")
Point [5 5] is in polygon: True Point [15 15] is in polygon: False Point [2 8] is in polygon: True Point [12 3] is in polygon: False
Alternative Approaches
| Method | Best For | Performance |
|---|---|---|
matplotlib.path |
General use, multiple points | Fast |
| Ray casting algorithm | Custom implementation | Medium |
| Shapely library | Complex geometric operations | Fast (uses C++) |
Conclusion
The matplotlib.path.Path method is the fastest built-in approach for point-in-polygon testing in Python. Use contains_point() for single points and contains_points() for batch processing multiple points efficiently.
