2D numpy ndarray的交叉点

Sub*_* S. 5 python opencv numpy

我有个问题.

我有两个numpy数组是OpenCV凸包,我想检查交集而不创建for循环或创建图像并对numpy.bitwise_and它们执行,这两者在Python中都很慢.数组看起来像这样:

[[[x1 y1]]
 [[x2 y2]]
 [[x3 y3]]
...
 [[xn yn]]]
Run Code Online (Sandbox Code Playgroud)

考虑[[x1 y1]]作为一个单独的元素,我想在两个numpy ndarray之间执行交集.我怎样才能做到这一点?我发现了几个类似性质的问题,但我无法从中找出解决方法.

提前致谢!

jte*_*ace 11

您可以使用数组视图作为intersect1d函数的单个维度,如下所示:

def multidim_intersect(arr1, arr2):
    arr1_view = arr1.view([('',arr1.dtype)]*arr1.shape[1])
    arr2_view = arr2.view([('',arr2.dtype)]*arr2.shape[1])
    intersected = numpy.intersect1d(arr1_view, arr2_view)
    return intersected.view(arr1.dtype).reshape(-1, arr1.shape[1])
Run Code Online (Sandbox Code Playgroud)

这将创建每个数组的视图,将每行更改为值的元组.然后它执行交集,并将结果更改回原始格式.以下是使用它的示例:

test_arr1 = numpy.array([[0, 2],
                         [1, 3],
                         [4, 5],
                         [0, 2]])

test_arr2 = numpy.array([[1, 2],
                         [0, 2],
                         [3, 1],
                         [1, 3]])

print multidim_intersect(test_arr1, test_arr2)
Run Code Online (Sandbox Code Playgroud)

这打印:

[[0 2]
 [1 3]]
Run Code Online (Sandbox Code Playgroud)


Sub*_* S. 1

这就是我为完成工作所做的:

import Polygon, numpy

# Here I extracted and combined some contours and created a convex hull from it.
# Now I wanna check whether a contour acquired differently intersects with this hull or not.

for contour in contours:  # The result of cv2.findContours is a list of contours
    contour1 = contour.flatten()
    contour1 = numpy.reshape(contour1, (int(contour1.shape[0]/2),-1))
    poly1 = Polygon.Polygon(contour1)

    hull = hull.flatten()  # This is the hull is previously constructued
    hull = numpy.reshape(hull, (int(hull.shape[0]/2),-1))
    poly2 = Polygon.Polygon(hull)

    if (poly1 & poly2).area()<= some_max_val:
        some_operations
Run Code Online (Sandbox Code Playgroud)

我必须使用 for 循环,这看起来有点乏味,尽管它给了我预期的结果。任何更好的方法将不胜感激!