我能想到的有7种
如果只是简单的按照如下的来找left up和right down的点进行计算是不能囊括全部情况的
按照计算机图形学的方法:
def cal_iou(box1, box2):
# 从x轴看无交点,直接不用计算
if box1[2] < box2[0] or box1[0] > box2[2]:
return -1
if box1[3] < box2[1] or box1[1] > box2[3]:
return -1
def cal_area(box):
return (box[2] - box[0]) * (box[3] - box[1])
area1 = cal_area(box1)
area2 = cal_area(box2)
# inner
x = [box1[0], box1[2], box2[0], box2[2]]
y = [box1[1], box1[3], box2[1], box2[3]]
# 排序
x.sort()
y.sort()
innerArea = abs(x[1]-x[2]) * abs(y[1]-y[2])
return innerArea / (area1 + area2 - innerArea)
该算法的思想是,不管是7种情况中的哪种,里面的矩形的宽高都能通过找到中间的两条线之间的距离进行计算
2022.7.15更新
一般用pytorch比较流行的实现方式如下:
def intersect(box_a, box_b):
A = box_a.size(0)
B = box_b.size(0)
max_xy = torch.min(box_a[:, 2:].unsqueeze(1).expand(A, B, 2),
box_b[:, 2:].unsqueeze(0).expand(A, B, 2))
min_xy = torch.max(box_a[:, :2].unsqueeze(1).expand(A, B, 2),
box_b[:, :2].unsqueeze(0).expand(A, B, 2))
inter = torch.clamp((max_xy - min_xy), min=0)
return inter[:, :, 0] * inter[:, :, 1]
box_a和box_b都是二维tensor,这样可以计算所有预测框和所有目标框之间排列组合的intersect