我的应用程序的一部分专门用于识别图像中所有对象的角。我发现了很多检测角点的方法,例如 Harris 角点检测和 GoodFeatureToTrack
。经过一些测试,GoodFeatureToTrack
已被证明是最佳解决方案,但我对多维数组的操作感到困惑。
我如何迭代这种类型的数组来检查点列表中是否有四个坐标形成一个正方形?
image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
corners = cv2.goodFeaturesToTrack(image, 150, 0.01, 15)
corners = np.int0(corners)
print("Points")
for corner in corners:
x, y = corner.ravel()
cv2.circle(image, (x, y), 5, (0, 0, 255), -1)
print(corners)
这是实际结果
积分
[[[141 265]]
[[148 176]]
[[136 360]]
[[233 358]]
[[192 218]]
[[130 465]]]
最佳答案
我写了一个函数,它在点列表中寻找形成正方形的点,如果存在则返回这四个点,如果不存在则返回 None
。对于列表中的任意两点,它首先计算它们的差异并将该向量旋转 90 度。然后它检查 point1 + 这个向量 和 point2 + 这个向量 或 point1 - 这个向量 和 point2 - 这个向量是否在列表中并且如果是这种情况,则返回它们。 diffRotated.any()
只是为了确保 point1 和 point2 不相同。
def findSquare(points):
for i, point1 in enumerate(points):
for point2 in points[i+1:]:
diffRotated = np.array([point2[1]-point1[1], point1[0]-point2[0]])
if (diffRotated.any() and np.any(points == point1 + diffRotated) and np.any(points == point2 + diffRotated)):
return np.array([point1, point2, point1 + diffRotated, point2 + diffRotated])
elif(diffRotated.any() and np.any(points == point1 - diffRotated) and np.any(points == point2 - diffRotated)):
return np.array([point1, point2, point1 - diffRotated, point2 - diffRotated])
return None
为了测试,我在您的列表中添加了两个条目,以便它们与您列表中的其他两个点形成一个正方形:
points = np.array([[141, 265],
[148, 176],
[136, 360],
[233, 358],
[192, 218],
[130, 465],
[145, 167],
[ 94, 214]])
print(findSquare(points))
# array([[141, 265],
# [192, 218],
# [ 94, 214],
# [145, 167]])
print(findSquare(points[:-1]))
# None
如果您想获得所有 方 block ,您需要修改我的代码并检查每个方 block 只返回一次。此外,这段代码效率不高,可能有一种我没有想到的方式以一种 numpy 时尚的方式来做到这一点。
关于python - 迭代多维数组并搜索形成正方形的点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54647994/