我有两个 OpenCV convex hulls 的 numpy 数组,我想在不创建 for 循环或创建图像并对它们执行 numpy.bitwise_and
的情况下检查交集,两者其中在 Python 中相当慢。数组看起来像这样:
[[[x1 y1]]
[[x2 y2]]
[[x3 y3]]
...
[[xn yn]]]
将 [[x1 y1]] 视为一个元素,我想在两个 numpy ndarray 之间执行交集。我怎样才能做到这一点?我发现了一些类似性质的问题,但我无法从那里找出解决方案。
最佳答案
您可以像这样将数组 View 用作 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])
这将创建每个数组的 View ,将每一行更改为值的元组。然后它执行交集,并将结果更改回原始格式。这是一个使用它的例子:
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)
这打印:
[[0 2]
[1 3]]
关于python - 二维多边形的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9269681/