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

时间:2018-01-27 15:09:38

标签: python python-3.x opencv coordinates cv2

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

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

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

1 个答案:

答案 0 :(得分:1)

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

您有一个间隔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从左侧与A相交intersection = b1 - a0

    b0  a0  b1  a1
        ==========
    ----------
    
  • B与右侧的A相交,intersection = a1 - b0

    a0  b0  a1  b1
    ==========
        ----------
    
  • B位于A左侧,intersection = 0

    b0  b1  a0  a1
            ======
    ------
    
  • B位于Aintersection = 0

    的右侧
    a0  a1  b0  b1
    ======
            ------
    

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

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