在OpenCV中绘制一个距离最近的4个点的矩形

Draw a rectangle with the closest 4 points in OpenCV

我有这些点(以像素为单位,2x2):

positions = [[120 321]
 [341 318]
 [538 304]
 [106 107]
 [540 102]
 [318  94]]

以 2D 形式绘制它们将如下所示:

我想找到有 4 个点的最小矩形,所以我想要这样的东西:

我尝试的是 Python:

rotated_rect = cv2.minAreaRect(positions)
box = cv2.boxPoints(rotated_rect)

但似乎 cv2.minAreaRect 不能像我希望的那样分成 2 个方格。

位置向量是随机给定的,所以我需要先重新排序得到矩形,而这些矩形是可以旋转的。

最后,这就是我计算它的方法。总之,我创建了一个函数来查找它们是否正在形成一个矩形:

def isRect(points):
    p1, p2, p3, p4 = points[0], points[1], points[2], points[3]
    cx = (p1[0] + p2[0] + p3[0] + p4[0]) / 4
    cy = (p1[1] + p2[1] + p3[1] + p4[1]) / 4

    d1 = int( math.sqrt( (cx-p1[0])**2 + (cy-p1[1])**2 ) )
    d2 = int( math.sqrt( (cx-p2[0])**2 + (cy-p2[1])**2 ) )
    d3 = int( math.sqrt( (cx-p3[0])**2 + (cy-p3[1])**2 ) )
    d4 = int( math.sqrt( (cx-p4[0])**2 + (cy-p4[1])**2 ) )

    if (d1 - 20 < d2 < d1 + 20 and
    d1 - 20 < d3 < d1 + 20 and
    d1 - 20 < d4 < d1 + 20):
        return True

    return False

准确的说,如果每个点到中心的距离都差不多(在我的例子中,阈值是20),那么它一定是一个矩形。

为了找到所有可能的情况,我使用了 itertools 库:

from itertools import combinations

for points in combinations(positions, 4):
    print( str(points) + " : " str(isRect(points)) )