使用原始点列表查找 Python / cv2 中重叠矩形的区域

Find area of overlapping rectangles in Python / cv2 with a raw list of points

我有一个矩形的坐标 x1y1x2y2 以及其他矩形的坐标列表。

我想将我已经拥有的那个与其他矩形的值进行比较,看它们是否重叠超过原始矩形的 50%

我检查了其他资源,但我仍然可以理解它:

让我们首先将您的问题简化为一个维度:

您有一个区间 A = [a0, a1],想知道另一个区间 B = [b0, b1] 与它相交多少。我将用 = 表示 A,用 - 表示 B

有 6 种可能的情况:

  • A 包含 Bintersection = b1 - b0

    a0  b0  b1  a1
    ==============
        ------
    
  • B 包含 Aintersection = a1 - a0

    b0  a0  a1  b1
        ======
    --------------
    
  • B 从左边相交 Aintersection = b1 - a0

    b0  a0  b1  a1
        ==========
    ----------
    
  • B 从右边相交 Aintersection = a1 - b0

    a0  b0  a1  b1
    ==========
        ----------
    
  • BA的左边,intersection = 0

    b0  b1  a0  a1
            ======
    ------
    
  • BA的右边,intersection = 0

    a0  a1  b0  b1
    ======
            ------
    

基于此,我们可以定义一个函数,给定两个区间A = [a0, a1]B = [b0, b1],returns它们相交的程度:

def calculateIntersection(a0, a1, b0, b1):
    if a0 >= b0 and a1 <= b1: # Contained
        intersection = a1 - a0
    elif a0 < b0 and a1 > b1: # Contains
        intersection = b1 - b0
    elif a0 < b0 and a1 > b0: # Intersects right
        intersection = a1 - b0
    elif a1 > b1 and a0 < b1: # Intersects left
        intersection = b1 - a0
    else: # No intersection (either side)
        intersection = 0

    return intersection

这几乎就是您需要的一切。要找出两个矩形相交多少,您只需要在 XY 轴上执行此函数并将这些量相乘以获得相交面积:

# The rectangle against which you are going to test the rest and its area:
X0, Y0, X1, Y1, = [0, 0, 10, 10]
AREA = float((X1 - X0) * (Y1 - Y0))

# Rectangles to check
rectangles = [[15, 0, 20, 10], [0, 15, 10, 20], [0, 0, 5, 5], [0, 0, 5, 10], [0, 5, 10, 100], [0, 0, 100, 100]]

# Intersecting rectangles:
intersecting = []

for x0, y0, x1, y1 in rectangles:       
    width = calculateIntersection(x0, x1, X0, X1)        
    height = calculateIntersection(y0, y1, Y0, Y1)        
    area = width * height
    percent = area / AREA

    if (percent >= 0.5):
        intersecting.append([x0, y0, x1, y1])

结果将是:

  • [15, 0, 20, 10] 不与 X 轴相交,所以 width = 0.
  • [0, 15, 10, 20] 不与 Y 轴相交,所以 height = 0.
  • [0, 0, 5, 5] 仅相交 25%.
  • [0, 0, 5, 10]50% 相交,将被添加到 intersecting
  • [0, 5, 10, 100]50% 相交,并将添加到 intersecting
  • [0, 0, 100, 100]100% 相交,并将添加到 intersecting