Skip to content Skip to sidebar Skip to footer

Testing Point With In/out Of A Vector Shapefile

Here is my question. 1. Intro a shapefile in polygon type represent the study area http://i8.tietuku.com/08fdccbb7e11c0a9.png some point located in the whole rectangle map http

Solution 1:

you can use shapely:

import numpy as np
from shapely.geometry import Polygon, Point

poly_data = [[0, 0], [0, 1], [1, 0], [0.2, 0.5]]
poly = Polygon(poly_data)

points = np.random.rand(100, 2)

mask = np.array([poly.contains(Point(x, y)) for x, y in points])

and here is the plot code:

import pylab as pl

fig, ax = pl.subplots()
ax.add_patch(pl.Polygon(poly_data))
ax.plot(points[:, 0], points[:, 1], "rx")
ax.plot(points[mask, 0], points[mask, 1], "ro")

the output:

enter image description here

You can also use MultiPoint to speed the calculation:

from shapely.geometry import Polygon, MultiPoint

poly_data = [[0, 0], [0, 1], [1, 0], [0.2, 0.5]]
poly = Polygon(poly_data)
points = np.random.rand(100, 2)
inside_points = np.array(MultiPoint(points).intersection(poly))

you can also use Polygon.contains_point() in matplotlib:

poly = pl.Polygon(poly_data)
mask = [poly.contains_point(p) for p in points]

Post a Comment for "Testing Point With In/out Of A Vector Shapefile"