如何对这个python函数进行矢量化以获取一个点数组(作为笛卡尔坐标对)?

时间:2018-03-07 15:33:30

标签: python python-3.x vectorization

我有这个函数检查一个点(作为一对笛卡尔坐标传递)是否在梯形内(作为顶点坐标的元组列表传递)

def inside(point_coordinates, trapezoid_vertices):
    x,y = point_coordinates
    is_inside = False
    x_1, y_1 = trapezoid_vertices[0]
    for i in range(1, 4):
        x_2, y_2 = trapezoid_vertices[i]
        if y > min(y_1, y_2):
            if y <= max(y_1, y_2):
                if x <= max(x_1, x_2):
                    if y_1 != y_2:
                        x_intersect = (y - y_1) * (x_2 - x_1) / (y_2 -y_1) + x_1
                    if x_1 == x_2 or x <= x_intersect:
                        is_inside = not is_inside
        x_1, y_1 = x_2, y_2
    return is_inside

我想让它接受一个numpy数组,其中数组的每个元素都是一对索引。然后我希望它返回一个bool数组,其中每个元素为True,如果与其索引相对应的点在梯形内,或者否则为False。例如,我要传递给函数的3x3数组如下所示:

a = [[[0 0]
      [0 1]
      [0 2]]

     [[1 0]
      [1 1]
      [1 2]]

     [[2 0]
      [2 1]
      [2 2]]]

我希望函数返回的是这样的:

[[ True  True False]
 [ True  True False]
 [False False False]]

我尝试使用inside_vectorized=np.vectorize(inside)对函数进行矢量化,但它似乎不起作用。运行inside_vectorized( a, [(0, 0), (0, 1), (1, 1), (1, 0)] )会给我一个TypeError。

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-6d5966fb40d4> in <module>()
----> 1 inside_vectorized(a, [(0, 0), (0, 1), (1, 1), (1, 0)])

/usr/lib/python3/dist-packages/numpy/lib/function_base.py in     __call__(self, *args, **kwargs)
   2205             vargs.extend([kwargs[_n] for _n in names])
   2206 
-> 2207         return self._vectorize_call(func=func, args=vargs)
   2208 
   2209     def _get_ufunc_and_otypes(self, func, args):

/usr/lib/python3/dist-packages/numpy/lib/function_base.py in _vectorize_call(self, func, args)
   2268             _res = func()
   2269         else:
-> 2270             ufunc, otypes =     self._get_ufunc_and_otypes(func=func, args=args)
   2271 
   2272             # Convert args to object arrays first

/usr/lib/python3/dist-packages/numpy/lib/function_base.py in _get_ufunc_and_otypes(self, func, args)
   2230             # arrays (the input values are not checked to ensure this)
   2231             inputs = [asarray(_a).flat[0] for _a in args]
-> 2232             outputs = func(*inputs)
   2233 
   2234             # Performance note: profiling indicates that -- for simple

<ipython-input-3-90f42f10d464> in inside(point_coordinates, trapezoid_vertices)
      9 
     10 def inside(point_coordinates, trapezoid_vertices):
---> 11     x,y = point_coordinates
     12 
     13     is_inside = False

TypeError: 'numpy.int64' object is not iterable

有人可以给我一个解决这个问题的起点吗?

0 个答案:

没有答案