yolo 算法中的IOU算法程序与原理解读

你如何判断对象检测算法运作良好呢?这里我们引进了IoU(Intersection over Union)

yolo 算法中的IOU算法程序与原理解读
通过上面的图,我们可以知道loU衡量了两个边界框重叠地相对大小。如果你有两个边界框,你可以计算交集,计算并集,然后求两个数值的比值,

yolo 算法中的IOU算法程序与原理解读

现在贴出python计算IOU代码:

def iou(box1, box2):
    """Implement the intersection over union (IoU) between box1 and box2

    Arguments:
    box1 -- first box, list object with coordinates (x1, y1, x2, y2)
    box2 -- second box, list object with coordinates (x1, y1, x2, y2)
    """

    # Calculate the (y1, x1, y2, x2) coordinates of the intersection of box1 and box2. Calculate its Area.
    ### START CODE HERE ### (≈ 5 lines)
    xi1 = max(box1[0], box2[0])
    yi1 = max(box1[1], box2[1])
    xi2 = min(box1[2], box2[2])
    yi2 = min(box1[3], box2[3])
    inter_area = (yi2 - yi1) * (xi2 - xi1)
    ### END CODE HERE ###

    # Calculate the Union area by using Formula: Union(A,B) = A + B - Inter(A,B)
    ### START CODE HERE ### (≈ 3 lines)
    box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1])
    box2_area = (box2[2] - box2[0]) * (box2[3] - box2[1])
    union_area = box1_area + box2_area - inter_area
    ### END CODE HERE ###

    # compute the IoU
    ### START CODE HERE ### (≈ 1 line)
    iou = inter_area / union_area
    ### END CODE HERE ###

    return iou

这里可以看出上面坐标系对应的box1的x1,y1,x2,y2和box2的x1,y1,x2,y2。

    xi1 = max(box1[0], box2[0])
    yi1 = max(box1[1], box2[1])
    xi2 = min(box1[2], box2[2])
    yi2 = min(box1[3], box2[3])
这段程序相当于计算出了交集的坐标系,通过这个交集的坐标系,可以求出交集的面积:

   inter_area = (yi2 - yi1) * (xi2 - xi1)

然后分别计算box1,box2的面积:

   box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1])
   box2_area = (box2[2] - box2[0]) * (box2[3] - box2[1])
现在计算box1与box2并集的面积,其为两个面积减去交集面积:

union_area = box1_area + box2_area - inter_area

最后计算IOU结果,交集面积/并集面积:

iou = inter_area / union_area

一般约定,在计算机检测任务中,如果,就说检测正确,如果预测器和实际边界框完美重叠,loU就是1,因为交集就等于并集。但一般来说只要,那么结果是可以接受的,看起来还可以。一般约定,0.5是阈值,用来判断预测的边界框是否正确。一般是这么约定,但如果你希望更严格一点,你可以将loU定得更高,比如说大于0.6或者更大的数字,但loU越高,边界框越精确。

本文参考:

1.http://www.ai-start.com/dl2017/html/lesson4-week3.html

2.https://blog.****.net/lanchunhui/article/details/71190055