Answer a question

I have been searching for a python alternative to MATLAB's inpolygon() and I have come across contains_points as a good option.

However, the docs are a little bare with no indication of what type of data contains_points expects:

contains_points(points, transform=None, radius=0.0)

Returns a bool array which is True if the path contains the corresponding point.

If transform is not None, the path will be transformed before performing the test.

radius allows the path to be made slightly larger or smaller.

I have the polygon stored as an n*2 numpy array (where n is quite large ~ 500). As far as I can see I need to call the Path() method on this data which seems to work OK:

poly_path = Path(poly_points)

At the moment I also have the points I wish to test stored as another n*2 numpy array (catalog_points).

Perhaps my problem lies here? As when I run:

in_poly = poly_path.contains_points(catalog_points)

I get back an ndarray containing False for every value no matter the set of points I use (I have tested this on arrays of points well within the polygon).

Answers

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

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐