求IoU代码

主要用来求RoI和GT的IoU, 也可以用来求预测结果和GT的IoU

def iou(boxes1, boxes2):
    """Computes IoU overlaps between two sets of boxes.
    boxes1, boxes2: [N, (y1, x1, y2, x2)].
    """
    # 1. Tile boxes2 and repeat boxes1. This allows us to compare
    # every boxes1 against every boxes2 without loops.
    # TF doesn't have an equivalent to np.repeat() so simulate it
    # using tf.tile() and tf.reshape().
    b1 = np.repeat(boxes1, np.shape(boxes2)[0], axis=0)
    b2 = np.tile(boxes2, [np.shape(boxes1)[0], 1])
    # 2. Compute intersections
    b1_y1, b1_x1, b1_y2, b1_x2 = np.split(b1, 4, axis=1)
    b2_y1, b2_x1, b2_y2, b2_x2 = np.split(b2, 4, axis=1)
    y1 = np.maximum(b1_y1, b2_y1)
    x1 = np.maximum(b1_x1, b2_x1)
    y2 = np.minimum(b1_y2, b2_y2)
    x2 = np.minimum(b1_x2, b2_x2)
    intersection = np.maximum(x2 - x1, 0) * np.maximum(y2 - y1, 0)
    # 3. Compute unions
    b1_area = (b1_y2 - b1_y1) * (b1_x2 - b1_x1)
    b2_area = (b2_y2 - b2_y1) * (b2_x2 - b2_x1)
    union = b1_area + b2_area - intersection
    # 4. Compute IoU and reshape to [boxes1, boxes2]
    iou = intersection / union
    overlaps = np.reshape(iou, [np.shape(boxes1)[0], np.shape(boxes2)[0]])
    return overlaps

 roi_iou_max = tf.reduce_max(overlaps, axis=1)

第一步即先把二者形状统一以方便逐个比较:

boxes1 = [[0,0,3,3], [1,1,5,5], [9,9,11,11]]
boxes2 = [[0,0,2,2], [1,1,3,3], [4,4,6,6], [6,6,9,9], [11,11,13,13]]
输出为
[[ 0  0  3  3]
 [ 0  0  3  3]
 [ 0  0  3  3]
 [ 0  0  3  3]
 [ 0  0  3  3]
 [ 1  1  5  5]
 [ 1  1  5  5]
 [ 1  1  5  5]
 [ 1  1  5  5]
 [ 1  1  5  5]
 [ 9  9 11 11]
 [ 9  9 11 11]
 [ 9  9 11 11]
 [ 9  9 11 11]
 [ 9  9 11 11]] 
[[ 0  0  2  2]
 [ 1  1  3  3]
 [ 4  4  6  6]
 [ 6  6  9  9]
 [11 11 13 13]
 [ 0  0  2  2]
 [ 1  1  3  3]
 [ 4  4  6  6]
 [ 6  6  9  9]
 [11 11 13 13]
 [ 0  0  2  2]
 [ 1  1  3  3]
 [ 4  4  6  6]
 [ 6  6  9  9]
 [11 11 13 13]]

之后的交集, 并集, IoU都是15x1的矩阵, 最后reshape成3x5的即[np.shape(boxes1)[0], np.shape(boxes2)[0]]代表把boxes1的每一项逐个和boxes2的每一项比较IoU, boxes1中同一个box得到的结果在同一行.

你可能感兴趣的:(求IoU代码)