inpolygon for Python - Examples of matplotlib.path.Path contains_points() method?
Often in these situations, I find the source to be illuminating...
We can see the source for path.contains_point
accepts a container that has at least 2 elements. The source for contains_points
is a bit harder to figure out since it calls through to a C function Py_points_in_path
. It seems that this function accepts a iterable that yields elements that have a length 2:
>>> from matplotlib import path
>>> p = path.Path([(0,0), (0, 1), (1, 1), (1, 0)]) # square with legs length 1 and bottom left corner at the origin
>>> p.contains_points([(.5, .5)])
array([ True], dtype=bool)
Of course, we could use a numpy array of points as well:
>>> points = np.array([.5, .5]).reshape(1, 2)
>>> points
array([[ 0.5, 0.5]])
>>> p.contains_points(points)
array([ True], dtype=bool)
And just to check that we aren't always just getting True
:
>>> points = np.array([.5, .5, 1, 1.5]).reshape(2, 2)
>>> points
array([[ 0.5, 0.5],
[ 1. , 1.5]])
>>> p.contains_points(points)
array([ True, False], dtype=bool)
Make sure that the vertices are ordered as wanted. Below vertices are ordered in a way that the resulting path is a pair of triangles rather than a rectangle. So, contains_points
only returns True
for points inside any of the triangles.
>>> p = path.Path(np.array([bfp1, bfp2, bfp4, bfp3]))
>>> p
Path([[ 5.53147871 0.78330843]
[ 1.78330843 5.46852129]
[ 0.53147871 -3.21669157]
[-3.21669157 1.46852129]], None)
>>> IsPointInside = np.array([[1, 2], [1, 9]])
>>> IsPointInside
array([[1, 2],
[1, 9]])
>>> p.contains_points(IsPointInside)
array([False, False], dtype=bool)
>>>
The output for the first point would have been True
if bfp3
and bfp4
were swapped.