二维numpy ndarray的交集 [英] Intersection of 2D numpy ndarrays
问题描述
我有一个问题.
我有两个numpy数组,它们是OpenCV凸包,并且我想检查交集而不创建循环或创建图像并对其执行numpy.bitwise_and
,这两个函数在Python中都非常慢.数组如下所示:
I have two numpy arrays that are OpenCV convex hulls and I want to check for intersection without creating for loops or creating images and performing numpy.bitwise_and
on them, both of which are quite slow in Python. The arrays look like this:
[[[x1 y1]]
[[x2 y2]]
[[x3 y3]]
...
[[xn yn]]]
考虑[[x1 y1]]作为一个元素,我想在两个numpy ndarray之间执行交集.我怎样才能做到这一点?我发现了一些性质相似的问题,但是我无法从那里找出解决方案.
Considering [[x1 y1]] as one single element, I want to perform intersection between two numpy ndarrays. How can I do that? I have found a few questions of similar nature, but I could not figure out the solution to this from there.
提前谢谢!
推荐答案
这就是我要做的工作:
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
我不得不使用for循环,尽管它给了我预期的结果,但是这看起来有点乏味.任何更好的方法将不胜感激!
I had to use for loop, and this altogether looks a bit tedious, although it gives me expected results. Any better methods would be greatly appreciated!
这篇关于二维numpy ndarray的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!