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

我想比较一个已经拥有的值和其他值,看它们是否重叠得比原始矩形的50%多。

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

  • https://codereview.stackexchange.com/questions/151309/check-if-two-rectangles-overlap
  • https://codereview.stackexchange.com/questions/31352/overlapping-rectangles
  • 最佳答案

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

    您有一个区间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
    ==========
        ----------
    
  • BAintersection = 0的左侧
    b0  b1  a0  a1
            ======
    ------
    
  • BAintersection = 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中。
  • 09-25 17:32