inpolygon for Python - Examples of matplotlib.path.Path contains_points() method?

后端 未结 3 2268
温柔的废话
温柔的废话 2021-02-05 23:07

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

3条回答
  •  孤独总比滥情好
    2021-02-05 23:37

    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)
    

提交回复
热议问题