- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What's the fastest way of checking if a point is inside a polygon in Python?
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
Advertisements