python - 求两个矩形的交集和并集

标签 python math geometry

我需要求两个矩形的交集和并集的面积,以及交集面积与并集面积的比率。做这个的最好方式是什么? Picture

def intersection_over_union(a, b):
    ax1 = a['left']
    ay1 = a['top']
    aw = a['width']
    ah = a['height']
    ax2 = ax1 + aw
    ay2 = ay1 + ah

    bx1 = b['left']
    by1 = b['top']
    bw = b['width']
    bh = b['height']
    bx2 = bx1 + bw
    by2 = by1 + bh

    delta_x = max(ax1, bx1) - min(ax2, bx2)
    delta_y = max(ay1, by1) - min(ay2, by2)

    overlap = delta_x * delta_y
    union = aw * ah + bw * bh - overlap

    print(overlap, union)

    return overlap / union

最佳答案

假设您正在处理 AABB(轴对齐边界框),这个小类定义了您需要的一切:

class Rect:
    def __init__(self, x, y, w, h):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
    
    def bottom(self):
        return self.y + self.h
    
    def right(self):
        return self.x + self.w
    
    def area(self):
        return self.w * self.h

    def union(self, b):
        posX = min(self.x, b.x)
        posY = min(self.y, b.y)
        
        return Rect(posX, posY, max(self.right(), b.right()) - posX, max(self.bottom(), b.bottom()) - posY)
    
    def intersection(self, b):
        posX = max(self.x, b.x)
        posY = max(self.y, b.y)
        
        candidate = Rect(posX, posY, min(self.right(), b.right()) - posX, min(self.bottom(), b.bottom()) - posY)
        if candidate.w > 0 and candidate.h > 0:
            return candidate
        return Rect(0, 0, 0, 0)
    
    def ratio(self, b):
        return self.intersection(b).area() / self.union(b).area()

if __name__ == "__main__":
    assert Rect(1, 1, 1, 1).ratio(Rect(1, 1, 1, 1)) == 1
    assert round(Rect(1, 1, 2, 2).ratio(Rect(2, 2, 2, 2)), 4) == 0.1111

关于python - 求两个矩形的交集和并集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68180297/

相关文章:

python - 使用 music21(python)从内核乐谱中获取零件 - 为什么找不到零件?

python - 如何计算一组线和一个点之间的(最小)距离?

python - 从整数创建球体包装最近邻列表

algorithm - 计算 'local convex hulls'并集的快速算法

python - 在 with 语句中或之前评估和分配表达式

python - python 中的 'object' s 属性是什么?

python - 无法将标准输出恢复为原始状态(仅限终端)

python - 在 Sympy 中设置变量相对于其他变量的假设

python - Python 中的自适应 ODE 算法

algorithm - 获取通过移动多边形创建的多边形