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

后端 未结 3 2319
温柔的废话
温柔的废话 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:46

    I wrote this function to return a array as in matlab inpolygon function. But this will return only the points that are inside the given polygon. You can't find the points in the edge of the polygon with this function.

    import numpy as np
    from matplotlib import path
    
    def inpolygon(xq, yq, xv, yv):
        shape = xq.shape
        xq = xq.reshape(-1)
        yq = yq.reshape(-1)
        xv = xv.reshape(-1)
        yv = yv.reshape(-1)
        q = [(xq[i], yq[i]) for i in range(xq.shape[0])]
        p = path.Path([(xv[i], yv[i]) for i in range(xv.shape[0])])
        return p.contains_points(q).reshape(shape)
    

    You can call the function as:

    xv = np.array([0.5,0.2,1.0,0,0.8,0.5])
    yv = np.array([1.0,0.1,0.7,0.7,0.1,1])
    xq = np.array([0.1,0.5,0.9,0.2,0.4,0.5,0.5,0.9,0.6,0.8,0.7,0.2])
    yq = np.array([0.4,0.6,0.9,0.7,0.3,0.8,0.2,0.4,0.4,0.6,0.2,0.6])
    print(inpolygon(xq, yq, xv, yv))
    

    As in the matlab documentation this function,

    returns in indicating if the query points specified by xq and yq are inside or on the edge of the polygon area defined by xv and yv.

提交回复
热议问题